Compare commits

...
Author SHA1 Message Date
joshua 101248195f Merge branch 'fix/church-from-accounts' 2026-12-01 00:54:27 +02:00
joshuaandClaude Opus 5.5 805967a85a events 3.9.0: SVG logos in PDFs (svg-to-pdfkit), the Accounts logo copied for PDFs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:54:25 +02:00
joshuaandClaude Opus 5.5 8055e1ec62 events 3.9.0, website 1.9.0, accounts 1.10.0: the church's details from Accounts everywhere
- Events: the Accounts profile's name, logo, icon, colours and contact details win over
  Events' own settings while Accounts is connected (pages, emails, WhatsApp, PDFs); Settings
  shows them read-only with a link to Accounts. The Accounts logo is copied for PDFs (PNG
  and JPEG). Fixes Events keeping its old church after a demo scenario load.
- Website: a background per homepage section in the church's colours; "More info" instead
  of "Register" for events without registration; the shared colour field.
- Accounts: the shared colour field in Church profile.
- @crosscode/ui 0.4.0: ColourField and isHexColour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:46:39 +02:00
joshua 799c193fe1 Merge branch 'docs/app-foundation' 2026-12-01 00:25:48 +02:00
joshuaandClaude Opus 5.5 f651ae2530 docs: the Hub runs 2.26.1 with two years of devotionals; App 1.0.0 on feat/app-scaffold
- Apps get 2 weeks of Cross Code's devotionals, today included.
- The App is built in slices on feat/app-scaffold (pushed, merged into
  main only when app@1.0.0 is done); the foundation is done.
- VERSIONS: the Hub at 2.26.1 in "Deployed / rolled out".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:25:48 +02:00
joshua 74dee881e4 Merge branch 'docs/handover-2.26.1' 2026-11-30 23:38:48 +02:00
joshuaandClaude Opus 5.5 969d0110a1 docs: Hub 2.26.1 and contracts 1.24.0 in the handover, plan and roadmap
The devotionals' two years ahead and 2-week fetch as a thing to
remember; the December CSV ready to import once the Hub is deployed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:38:47 +02:00
joshua fd097d8446 Merge branch 'feat/devotionals-two-years' 2026-11-30 23:23:19 +02:00
joshuaandClaude Opus 5.5 9cf2956aff contracts 1.24.0: devotionals two years ahead; Apps fetch 2 weeks
CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS (24) for how far ahead the Hub
schedules Cross Code's devotionals, CROSSCODE_DEVOTIONALS_FETCH_DAYS (14)
for what GET /api/v2/devotionals answers. The CSV takes 800 rows and
8 MB, so two years fit in one file. CROSSCODE_DEVOTIONALS_AHEAD_MONTHS
kept, deprecated. Docs: Hub 2.26.1, hub-protocol.md §3c, the App plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:23:18 +02:00
joshua 986d69d51d Merge branch 'docs/hub-2.26' 2026-11-30 22:25:15 +02:00
joshuaandClaude Opus 5.5 d3789f9b30 docs: Hub 2.26.0 released; devotionals endpoint in hub-protocol.md
Hub 2.26.0 (the App from New install, demo scenarios, devotionals) in
VERSIONS.md, the handover and APP-1.0-PLAN, not deployed yet; §3c in
hub-protocol.md for GET /api/v2/devotionals (same as events-hub's copy).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:25:15 +02:00
joshua ce169851f7 Merge branch 'docs/phase6-website-agent' 2026-11-30 16:30:02 +02:00
joshuaandClaude Opus 5.5 0b518761b7 docs: Website 1.8.0, agent 1.7.0 and contracts 1.23.0 in every handover and plan
ROADMAP phase 6, the root README (packages/demo in the Website), the contracts README
(seed-scenario), AGENT-1.0-PLAN's job table (seed-demo for every product, seed-scenario),
VERSIONS' Website row, and HANDOVER's demo-scenario rule (one job, whatever is installed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:29:58 +02:00
joshua a5e3a6bb6c Merge branch 'feat/agent-1.7' 2026-11-30 16:25:32 +02:00
joshuaandClaude Opus 5.5 2e8e4c04ca agent 1.7.0 + contracts 1.23.0: a demo scenario seeds whatever the church has installed
- contracts 1.23.0: the seed-scenario job (church, scenario, optional adminEmail; 45 minutes),
  SEED_SCENARIO_JOB_MIN_AGENT 1.7.0.
- agent 1.7.0: seed-scenario -> `crosscode demo <church> --scenario <s>`; seed-demo for
  accounts and app, and --scenario passed on to every product.
- crosscode script: `crosscode demo <church> --scenario <s>` loads the scenario on every product
  the church has here (Accounts, Events, the Website, the App), skipping the rest; every
  installed release checked first; the first failure stops the rest and names what's out of
  step (loaded / skipped in the report). `crosscode demo <church> app` says the App's demo comes
  with App 1.0.0.
- Docs: HANDOVER, APP-1.0-PLAN, VERSIONS, CHANGELOG, agent What's New.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:25:31 +02:00
joshua 7391f97cfa Merge branch 'feat/website-1.8' 2026-11-30 15:25:51 +02:00
joshuaandClaude Opus 5.5 c8e270dbf1 website 1.8.0: demo scenarios (the scenario's people lead, Events' events through the feed)
- `npm run demo -- --profile <p> --scenario <p>`: each profile's `scenarioTeam` names four
  parts, roles and portraits; the names are the scenario's people from @crosscode/demo, the
  pastor first (home page and messages' speaker).
- With a linked Cross Events, a scenario load makes no events of its own, turns on Show events
  from and fetches Events' whole feed at once; an unreachable Events doesn't fail the load.
- A scenario on a site with no church profile saves the scenario's church, not Acacia Hill.
- crosscode script: `crosscode demo <church> website --scenario` passes it on and refuses a
  Website before 1.8.0; the Website installs and builds packages/demo.
- Docs: HANDOVER, APP-1.0-PLAN, VERSIONS, CHANGELOGs, What's New.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:23:12 +02:00
joshua b2a163bb39 Merge branch 'feat/contracts-1.22-bible-notices' 2026-11-30 13:48:39 +02:00
joshuaandClaude Opus 5.5 2eef8d1da3 contracts 1.22.0: only free Bible translations in App 1.0, the publishers' notices
- Each translation has a licence; FREE_BIBLE_TRANSLATION_IDS (KJV and the new
  Berean Standard Bible) is what the Hub and App 1.0 offer, and the CSV import
  refuses any other when told to, naming the publisher to ask.
- The publishers' exact notices (NLT, ESV, AFR53, AFR83 corrected), an
  acknowledgement per translation, the Bible Society's disclaimer, publisher
  and permissionsUrl, FREE_QUOTE_VERSES and quotedVerses. AFR83 is named
  "Afrikaans 1983/1992-vertaling".
- docs/BIBLE-PERMISSIONS.md: what each publisher allows, the status and the
  drafted permission requests. APP-1.0-PLAN decision 14, HANDOVER (with the
  Website 1.8.0 approach), VERSIONS, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:48:38 +02:00
joshua dfd7278f7b Merge branch 'docs/phase6-progress' 2026-11-30 11:47:31 +02:00
joshuaandClaude Opus 5.5 aacfd228a6 docs: phase 6 progress in every handover, README and plan
HANDOVER (phase table, released 2026-11-30, next steps, demo scenarios, WhatsApp
STOP rule, local PostgreSQL), ROADMAP phase 5/6, APP-1.0-PLAN status, the root
README's folders, Events' handover / FEATURES / DEMO_DATA / README for STOP and
the scenarios, Accounts' and @crosscode/demo's READMEs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:47:29 +02:00
joshua e32d9ecb09 Merge branch 'feat/events-3.8' 2026-11-30 11:42:19 +02:00
joshuaandClaude Opus 5.5 49153e6f07 Events 3.8.0, @crosscode/demo 1.1.0: STOP stops all WhatsApp, demo scenarios
Events 3.8.0 (one migration):
- STOP to the church's WhatsApp number stops all WhatsApp, not only news:
  checked before every sendText/sendPdf against WhatsAppStop (by number) and
  User.whatsappOptedOut (from Accounts' user.updated); 2FA codes go by email
- a STOP received here is passed on to Accounts (whatsapp.optout); START turns
  it back on without Accounts; Accounts turning it back on clears it here
- the eight demo scenarios as set-demo profiles, around each church's own
  people (@crosscode/demo, same accounts as Accounts) and campuses; the
  scenario's people are never removed from Accounts

@crosscode/demo 1.1.0: each person's gender.
crosscode script: scenarios as Events demo profiles; Events builds packages/demo.

Checked on PostgreSQL 18: the migration and every scenario loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:42:17 +02:00
joshua 5b9dc559b6 Merge branch 'feat/accounts-1.9' 2026-11-30 11:05:24 +02:00
joshuaandClaude Opus 5.5 ad488c3280 Accounts 1.9.0, @crosscode/demo 1.0.0: messaging.get, WhatsApp opt-out, demo scenarios
Accounts 1.9.0 (one migration):
- messaging.get (sealed settings) and the messaging.changed hint to products
  that asked, on admin or product changes
- the WhatsApp opt-out for every product: whatsapp.optout, Accounts' own WAWP
  webhook, WhatsAppOptOut kept per number, whatsapp_opted_out in user.updated,
  no WhatsApp from Accounts to an opted-out person, "Turn WhatsApp back on"
- demo scenarios: npm run demo -- --profile <scenario> --force replaces the
  church profile (with an SVG logo and icon at /api/demo-assets/) and the demo
  people, ids kept across loads

@crosscode/demo 1.0.0 (new): the eight scenarios' churches, people and logos.

crosscode script: crosscode demo <church> accounts, --scenario on every demo,
Accounts installs and builds packages/demo.

Checked on PostgreSQL 18: migrations, scenario loads, opt-out, npm run demo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:05:22 +02:00
joshua 50ac7fab33 Merge branch 'feat/contracts-1.21' 2026-11-30 10:11:48 +02:00
joshuaandClaude Opus 5.5 7032e16894 contracts 1.21.0: demo scenarios, eight churches across every product
agent.DEMO_SCENARIOS (one per Website demo profile, each its own fictional
church), DEMO_SCENARIO_ORDER (Accounts first), DEMO_SCENARIO_MIN_VERSIONS,
scenario in seed-demo, accounts in DEMO_PRODUCTS, a profile per scenario for
Events and the App, SEED_SCENARIO_MIN_AGENT (1.7.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:11:46 +02:00
joshua b720706143 Merge branch 'docs/app-demo-scenarios' 2026-11-30 10:03:36 +02:00
joshuaandClaude Opus 5.5 5380a87be1 docs: App 1.0 plan, eight demo scenarios, each its own church with logo and details
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:03:36 +02:00
joshuaandClaude Opus 5.5 bd472ddc05 docs: App 1.0 plan, demo scenarios across every product; contracts 1.20.0 recorded as released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:56:16 +02:00
joshua c22d7ecad6 Merge branch 'feat/contracts-1.20' 2026-11-30 09:54:45 +02:00
joshuaandClaude Opus 5.5 514a6d8bc0 contracts 1.20.0: devotionals, Bible passages, messaging.get, WhatsApp opt-out, App export
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12). Additive.

- crosscode.devotional/1, the Hub's devotionals reply, and the devotionals CSV
  import (parseCsv, checkDevotionalCsv, template), shared by the Hub and the App
- Bible books (USFM, English and Afrikaans), seven translations with YouVersion
  ids and copyright lines, parseBibleReference, youVersionUrl
- messaging.get and the messaging.changed hint; whatsapp.optout and
  whatsapp_opted_out on the profile
- APP_MODULES, hub.DEVOTIONALS_PATH, agent.APP_DEMO_PROFILES, app in DEMO_PRODUCTS
- the app section of the church export, people[].roles
- Accounts refuses the two new requests until 1.9.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:54:25 +02:00
joshua 8372ef8c6b Merge branch 'docs/app-1.0-plan' 2026-11-30 09:28:21 +02:00
joshuaandClaude Opus 5.5 250c631fb4 docs: Church App 1.0 plan, phase 5 recorded as done
APP-1.0-PLAN.md plans phase 6 (House of Prayer as a 24-hour clock,
prayer requests with approval, announcements, devotionals from Cross
Code or the church's own with a Hub CSV import and YouVersion links,
events, shared email and WhatsApp through Accounts), with Joshua's
decisions of 2026-11-30 and a link to the mockup.

HANDOVER.md records phase 5 as rolled out (Hope Family Church and a
second church live) and sets phase 6 as next up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:28:20 +02:00
joshua 753e2c4631 Merge branch 'docs/deployed-website-1.7.1' 2026-11-30 07:53:05 +02:00
joshuaandClaude Opus 5.5 42684ed727 docs: Website 1.7.1 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:53:03 +02:00
joshua 1e3004189a Merge branch 'feat/website-framing-everywhere' 2026-11-28 00:30:26 +02:00
joshuaandClaude Opus 5.5 0c521ff614 Website 1.7.1: move and zoom for ministries', leaders' and events' photos
1.7.0 had Move and zoom in page sections only. Ministries, Leadership
and Events now have it on their photo, in the frame the site uses for
the current template and layouts. Saved with the row as `framing`
({ x, y, zoom }, null for centred; cleared when the photo changes).
Ministries and leaders are drafts until Publish (snapshot, Discard and
Restore carry it); an event's shows once the event is published.
Versions published before this compare unchanged.

One migration: a nullable JSONB `framing` column on Ministry, Leader
and SimpleEvent.

Also: the 1.7.0 e2e test waits for the media library to load before
counting it (it could count an empty list).

Checked: Website backend tests (136) and typecheck, frontend typecheck
and lint, production build, admin e2e suite in Chromium (12).
Lighthouse not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:27:54 +02:00
joshua 4897489fb1 Merge branch 'docs/all-on-latest' 2026-11-28 00:06:12 +02:00
joshuaandClaude Opus 5.5 1c69b0cce9 docs: everything deployed on latest (crosscode.co.za 1.9.1; old rollout notes closed)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:06:11 +02:00
joshua b3318941ae Merge branch 'docs/deployed-table-website-1.7.0' 2026-11-28 00:04:49 +02:00
joshuaandClaude Opus 5.5 2efafa166e docs: Hub 2.25.1 deployed; deployed table catches up with Events 3.7.2 and Website 1.7.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:04:48 +02:00
joshua e0c82fe314 Merge branch 'docs/hub-2.25.1' 2026-11-27 23:47:07 +02:00
joshuaandClaude Opus 5.5 a474cdcda6 docs: Hub 2.25.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:47:07 +02:00
joshua 8234bb3bc1 Merge branch 'docs/deployed-website-1.7.0' 2026-11-27 23:41:54 +02:00
joshuaandClaude Opus 5.5 dd86021302 docs: Website 1.7.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:41:53 +02:00
joshua 19c12ef09e Merge branch 'feat/website-photo-framing' 2026-11-27 23:34:10 +02:00
joshuaandClaude Opus 5.5 a9215ac4e4 Website 1.7.0: move and zoom photos in their frame; delete unused photos
- A section's photo (hero, welcome, invitation, image-text) shows in the
  shape of its frame for the current template and layout, with a Move and
  zoom dialog: drag or arrow keys to choose what stays in view, zoom to
  300%. Saved with the section as data.framing ({ x, y, zoom } by media
  id), a draft until published. The site draws it with object-position
  and scale() around that point; Bold split/collage frames now clip, and
  a zoomed photo stays inside Heritage's mat. Framing for photos a section
  no longer shows is dropped on save.
- Media library: each photo says where it's used; one used nowhere can be
  deleted with its files (DELETE /admin/media/:id, 409 IN_USE otherwise,
  audited as media_deleted).

Checked: Website backend tests (135) and typecheck, frontend typecheck,
lint and production build, and an e2e test of both flows in Chromium.
Lighthouse not run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:34:10 +02:00
joshua 25100bd749 Merge branch 'docs/deployed-events-3.7.2-website-1.6.1' 2026-11-27 15:41:07 +02:00
joshuaandClaude Opus 5.5 f68f695934 docs: Events 3.7.2 and Website 1.6.1 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:41:05 +02:00
joshua ebcee43594 Merge branch 'fix/feed-after-reseed' 2026-11-27 15:35:42 +02:00
joshuaandClaude Opus 5.5 7f681c9e81 Events 3.7.2 + Website 1.6.1: no duplicate events after a reseed; "Events site" in the header
A reseed gives every event a new id without listing the old ones in the
feed's `deleted`, and consumers only fetched ?updatedSince= after the first
sync, so the old copies stayed beside the new ones.

- Both: the 15-minute feed poll and "Sync now" fetch the whole list and
  drop copies that aren't in it; the fetch after event.changed stays
  incremental.
- Events set-demo.js keeps FeedEntry and marks its live entries removed,
  resets the links' lastGoodAt, then publishes the new feed, sends
  event.changed and fetches the linked products' events back in.
- Website loadDemo lists the old published events in FeedRemoval and sends
  event.changed after publishing.
- Website header: links to the church's other sites read "Events site"
  with an external-link icon, not a second "Events".

Checked: Website backend tests (133), Events backend tests (802), both
typechecks, Website frontend build. set-demo.js not run end to end (no
local database).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:35:38 +02:00
joshua a75d2f7b46 Merge branch 'docs/released-site-1.9.1' 2026-11-27 15:13:39 +02:00
joshuaandClaude Opus 5.5 2edb9f681a docs: crosscode.co.za 1.9.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:13:38 +02:00
joshua d299442015 Merge branch 'docs/deployed-everything' 2026-11-27 15:09:29 +02:00
joshuaandClaude Opus 5.5 9994cbd760 docs: everything deployed on the latest releases
Hub 2.25.0, agent 1.6.0 (church-server1 and the central server), Cross Events
3.7.1 and Accounts 1.8.0 at the churches, the Church Website 1.6.0 on
cross-demo2, crosscode.co.za 1.9.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:09:29 +02:00
joshua 0d6afc7cd1 Merge branch 'docs/released-site-1.9.0' 2026-11-27 15:06:25 +02:00
joshuaandClaude Opus 5.5 3539bf0ac0 docs: crosscode.co.za 1.9.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:06:24 +02:00
joshua ff3d9aefa2 Merge branch 'docs/released-site-1.8.1' 2026-11-27 14:55:00 +02:00
joshuaandClaude Opus 5.5 8c4f5f244c docs: crosscode.co.za 1.8.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:55:00 +02:00
joshua edac4ee767 Merge branch 'test/website-demo-profile' 2026-11-27 14:47:01 +02:00
joshuaandClaude Opus 5.5 090453e14a test: the Website e2e server loads a demo profile (/test/demo?profile=); docs: crosscode.co.za 1.8.0 released
For the crosscode-site screenshots of another church on each template. Test
helper only, no Website release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:47:01 +02:00
joshua 9c87208428 Merge branch 'docs/released-website-1.6.0' 2026-11-27 14:32:15 +02:00
joshuaandClaude Opus 5.5 f931226e74 docs: Website 1.6.0 and crosscode.co.za 1.7.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:32:14 +02:00
joshua 1940ff2a91 Merge branch 'feat/website-demo-photos' 2026-11-27 14:32:04 +02:00
joshuaandClaude Opus 5.5 2d4d9ea871 Website 1.6.0: real photos for the demo church, photos sized to their frames
The demo church (and the eight demo profiles) used one generated "hills and
sun" SVG for every picture. Now 104 Unsplash stock photos (models; free under
the Unsplash License, credited in backend/demo-photos/CREDITS.md): a set per
profile, a portrait for every leader (before: only the pastor), a picture for
each event, and a photo for each message instead of the stand-in video's
thumbnail. Demo photos go through processImage like an upload, made once per
machine and copied; without demo-photos/ the illustration still stands in.

A message's thumbnailUrl that is one of the site's own uploads now comes
before the YouTube thumbnail; admins and the YouTube feed store YouTube's
address there, so a church's own messages are unchanged.

Faster on phones: the Community collage hero, the collage row, the team's
portraits and the ministry cards give the browser their real width (sizes),
so a phone no longer fetches the full-width photo for a small frame.

Checked: backend tests (131), Website e2e (130, baselines retaken;
Lighthouse mobile 90-98 performance, 100 accessibility and SEO), typecheck,
lint and both builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:31:57 +02:00
joshua 28085d92ba Merge branch 'docs/deployed-hub-2.25.0-agent-1.6.0' 2026-11-27 10:07:34 +02:00
joshuaandClaude Opus 5.5 fbe814b2d9 docs: Hub 2.25.0 and agent 1.6.0 deployed (Website still 1.2.0 on cross-demo2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:07:34 +02:00
joshua fe4310352e Merge branch 'docs/released-website-1.5.0' 2026-11-27 10:04:58 +02:00
joshuaandClaude Opus 5.5 db12d17796 docs: Website 1.5.0 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:04:57 +02:00
joshua 22d7e54008 Merge branch 'feat/website-uploads-backup' 2026-11-27 10:04:39 +02:00
joshuaandClaude Opus 5.5 8c213d6d84 Website 1.5.0: back up the photos and files too
The nightly backup (and Back up now) snapshots backend/uploads after the
database, into backups/uploads-YYYYMMDD-HHMMSS/. Unchanged files are hard
links to the last snapshot, so after the first full copy a night costs
only the new files. Built in a partial folder and renamed when complete,
refused up front when the disk hasn't room, kept to the same count as the
database backups, with its own switch on Admin -> Backups.

crosscode script: an uninstall keeps the Website's backups with rsync -aH,
so the snapshots' shared files stay shared.

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:20:09 +02:00
joshua 81c01d8a9f Merge branch 'docs/deployed-hub-2.24.1-website-1.2.0' 2026-11-27 08:44:56 +02:00
joshuaandClaude Opus 5.5 2335fd46e4 docs: Hub 2.24.1 deployed, Website 1.2.0 on cross-demo2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:44:55 +02:00
joshua f58711603a Merge branch 'docs/hub-2.24.1' 2026-11-27 08:36:19 +02:00
joshuaandClaude Opus 5.5 d1354a6a17 docs: Hub 2.24.1 released
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:36:18 +02:00
joshua 175a6b41eb Merge branch 'docs/hub-2.24.0' 2026-11-27 08:30:15 +02:00
joshuaandClaude Opus 5.5 80d8e903dd docs: Hub 2.24.0 deployed (Website 1.2.0 not on cross-demo2 yet)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:30:15 +02:00
303 changed files with 12802 additions and 563 deletions
+248
View File
@@ -2,6 +2,254 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## events@3.9.0 + website@1.9.0 + accounts@1.10.0 - 2026-12-01
The church's details from Accounts on every site, section backgrounds, one colour picker (Joshua,
2026-12-01). No migrations; no contracts change.
- **Events 3.9.0:** the Accounts profile's name, logo, icon, colours and contact details win over
Events' own settings while Accounts is connected (pages, emails, WhatsApp, PDFs), and Settings
shows them read-only with a link to Accounts. The logo from Accounts is copied for PDFs, and SVG logos
are drawn in PDFs (`svg-to-pdfkit`, new dependency). Fixes Events keeping its old church after a demo scenario load.
- **Website 1.9.0:** a background for each homepage section in the church's colours; "More info"
instead of "Register" for events without registration; the shared colour field in Church
details.
- **Accounts 1.10.0:** the shared colour field in Church profile.
- **`@crosscode/ui` 0.4.0:** `ColourField` and `isHexColour`.
- Checked: Events backend tests (828), Website backend tests (149), typecheck and lint of every
changed app.
## contracts@1.24.0 - 2026-11-30
Cross Code's devotionals two years ahead, and Apps fetch 2 weeks (Joshua, 2026-11-30). Additive.
- `CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS` (24): how far ahead the Hub schedules them.
- `CROSSCODE_DEVOTIONALS_FETCH_DAYS` (14): the most days one `GET /api/v2/devotionals` answer
covers, `from` included. `CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3) is kept but deprecated.
- The devotionals CSV takes 800 rows and 8 MB (was 400 and 2 MB), so two years fit in one file; a
date past `latestDate` says "too far ahead (the last day is …)" instead of naming 3 months.
- Checked: contracts' tests (341), typecheck.
## agent@1.7.0 + contracts@1.23.0 + crosscode script - 2026-11-30
Church App 1.0.0 groundwork in the server agent (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
- **Contracts 1.23.0:** the `seed-scenario` job (`church`, `scenario`, optional `adminEmail`; 45
minutes): a whole demo scenario in one job, on whatever the church has installed.
`SEED_SCENARIO_JOB_MIN_AGENT` (1.7.0). Additive.
- **Agent 1.7.0:** `seed-scenario` → `crosscode demo <church> --scenario <s>`; `seed-demo` for `accounts` and `app` (`crosscode demo <church> <product> …`),
and `scenario` passed on as `--scenario` for every product (contracts `SEED_SCENARIO_MIN_AGENT`,
`SEED_APP_DEMO_MIN_AGENT`). Events' jobs keep their old form (no product).
- **crosscode script:** `crosscode demo <church> --scenario <s>` (no product, no profile) loads the
scenario on every product the church has here, in deploy order, skipping the others; checks
every installed release against the scenario minimums first; each product takes its own
backup; the first failure stops the rest and names what's out of step (`loaded`, `skipped` in
the report). Events' demo is now `cmd_demo_events`. `crosscode demo <church> app …` says the
App's demo comes with App 1.0.0, instead of misreading `app` as a second church.
## website@1.8.0 + crosscode script - 2026-11-30
Church App 1.0.0 groundwork in the Church Website (docs/APP-1.0-PLAN.md §12, "Demo scenarios"). No
migration. Details in `apps/website/CHANGELOG.md`.
- **Website 1.8.0:** `npm run demo -- --profile <p> --scenario <p>` loads a profile as part of its
demo scenario: the leaders are the scenario's people (`@crosscode/demo`), the pastor the home
page's and the messages' speaker; with a linked Cross Events, Events' events show through the
feed (Show events from, fetched at once) instead of the profile's own.
- **crosscode script:** `crosscode demo <church> website … --scenario <p>` passes it on and refuses a
Website before 1.8.0; the Website installs and builds `packages/demo`.
## contracts@1.22.0 - 2026-11-30
Bible translations for the Church App's devotionals (docs/BIBLE-PERMISSIONS.md, APP-1.0-PLAN.md §6
and decision 14). Additive except for the notice texts and one translation's name; no id changes,
nothing has shown them yet.
- **Only free translations in 1.0:** each translation has a `licence` ("public-domain" or
"permission"); `FREE_BIBLE_TRANSLATION_IDS` (KJV, BSB) is what the Hub and the App offer, and
`checkDevotionalCsv(text, { translations })` refuses any other, naming the publisher to ask.
- **The Berean Standard Bible (`BSB`)**, public domain since 2023, YouVersion 3034. The CSV template
and the devotionals sample now quote the BSB and the KJV.
- **Notices corrected** to each publisher's current wording: NLT (Tyndale House Ministries), ESV
(ESV Text Edition: 2025, the Creative Commons and translation clauses), AFR53 and AFR83 (the
Bible Society's digital short form). The NIV and NKJV notices were already right.
- **`AFR83` is named "Afrikaans 1983/1992-vertaling"**, as the Bible Society names it.
- **New per translation:** `acknowledgement` (the full notice, for the App's Acknowledgements
page), `disclaimer` (the Bible Society's, required with its translations next to content it
hasn't approved; null for the others), `publisher` and `permissionsUrl` (null for the KJV).
- **`FREE_QUOTE_VERSES`** (500) and **`quotedVerses(passages)`**: verses quoted per translation,
so the Hub and the App can warn before the free allowance runs out. `devotionalDisclaimer`.
## events@3.8.0 + @crosscode/demo 1.1.0 + crosscode script - 2026-11-30
Church App 1.0.0 groundwork in Cross Events (docs/APP-1.0-PLAN.md §8 and §12). One migration.
Details in `apps/events/CHANGELOG.md`.
- **Events 3.8.0:** STOP stops all WhatsApp (not only news), checked before every message, kept by
number and per account (`whatsapp_opted_out` from Accounts), passed on to Accounts
(`whatsapp.optout`); START turns it back on without Accounts. The eight demo scenarios
(`set-demo.js --profile=<scenario>`), built around the scenario's own people and campuses.
- **`@crosscode/demo` 1.1.0:** each person's `gender` (for Events' gendered events and cabins).
- **crosscode script:** Events takes the scenarios as demo profiles; Events installs and builds
`packages/demo`.
## accounts@1.9.0 + @crosscode/demo 1.0.0 + crosscode script - 2026-11-30
Church App 1.0.0 groundwork in Accounts (docs/APP-1.0-PLAN.md §8 and §12). One migration. Details
in `apps/accounts/CHANGELOG.md`.
- **Accounts 1.9.0:** `messaging.get` and the `messaging.changed` hint (the App sends with the
church's one set of email and WhatsApp settings); the WhatsApp opt-out for every product
(`whatsapp.optout`, its own WAWP webhook for a church without Events, `whatsapp_opted_out` in
`user.updated`, "Turn WhatsApp back on" on the account page); a demo scenario's church profile,
logo, icon and people (`npm run demo -- --profile <scenario> --force`).
- **`@crosscode/demo` 1.0.0** (new, `packages/demo`, not tagged): the eight scenarios' churches,
people (same `sub` in every product) and SVG logos, for every product's demo loader.
- **crosscode script:** `crosscode demo <church> accounts --profile <scenario>` (backup, load,
reload); `--scenario <s>` on every demo (the profile must be the scenario's); Accounts installs
and builds `packages/demo`.
## contracts@1.21.0 - 2026-11-30
Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the
Hub loads every product with the same church. Additive for `seed-demo` jobs older Hubs send.
- **`agent.DEMO_SCENARIOS`**: eight, one per Website demo profile and keyed by it, each its own
fictional church (St Columba's, Grace Cathedral, Ignite Church, Harbour City, Acacia Hill, Karoo
Gemeenskapskerk, Northpoint, Riverside) with a label, description, campuses, language, the App's
active-member band, and the profile each product loads. `demoScenario(key)`,
`DEMO_SCENARIO_ORDER` (Accounts, Events, Website, App), `DEMO_SCENARIO_MIN_VERSIONS` (Accounts
1.9.0, Events 3.8.0, Website 1.8.0, App 1.0.0).
- **`seed-demo`** takes an optional `scenario`; its `profile` must then be the scenario's for the
product. `accounts` joins `DEMO_PRODUCTS` (the scenario's church profile, logo, icon and people;
no `adminEmail`). Events gets a profile per scenario next to its four (`EVENTS_DEMO_PROFILES`),
so a scenario name with no `product` is an Events demo.
- **`APP_DEMO_PROFILES`** is the eight scenarios. 1.20.0's `acacia-hill` is gone: it's the
`community-family` scenario, and no App or Hub had used it.
- `SEED_SCENARIO_MIN_AGENT` (1.7.0) and `SEED_DEMO_MIN_AGENT_BY_PRODUCT`. JSON Schema `agent-job`
regenerated.
## contracts@1.20.0 - 2026-11-30
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12), the first step of phase 6. Additive:
products on 1.19.0 keep working. Accounts refuses the two new requests (`INVALID_REQUEST`) until
Accounts 1.9.0 answers them.
- **`crosscode.devotional/1`** (`src/devotional.ts`): `devotionalSchema` (date, title, the passage
with its text and translation, body, prayer, author, `source` `crosscode` or `church`),
`devotionalsReplySchema` (the Hub's `GET /api/v2/devotionals?from=`, Cross Code's only),
`CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3). **CSV import** shared by the Hub and the App:
`DEVOTIONAL_CSV_COLUMNS`, `parseCsv` (quotes, line breaks, BOM, `;` files), `checkDevotionalCsv`
(each row's errors by column, warnings, days already taken, a `latestDate` limit, dates twice in
the file), `devotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`.
- **Bible passages** (`src/bible.ts`): `BIBLE_TRANSLATIONS` (NLT, ESV, NIV, NKJV, KJV, AFR53, AFR83,
each with its YouVersion id and copyright line), `BIBLE_BOOKS` (USFM codes, English and Afrikaans
names, abbreviations, chapters), `parseBibleReference` ("Johannes 3:16–18", "1 Kor. 13:4-7",
"Rom 8:38-9:1", "Jude 3"), `formatBibleReference`, `passageVerseCount`, `youVersionUrl`,
`PASSAGE_WARN_VERSES` (25).
- **Identity requests:** `messaging.get` (the church's SMTP and WAWP settings for the App, secrets
sealed with the link's secret; `messagingGetReplySchema`) and the `messaging.changed` hint
Accounts sends back (`MESSAGING_CHANGED_PATH`); `whatsapp.optout` (a STOP received by any
product; `whatsappOptOutReplySchema`). `whatsapp_opted_out` (optional) in the profile that
`user.updated` and the sign-in claims carry.
- **App:** `APP_MODULES`; `hub.DEVOTIONALS_PATH` and its error codes; `agent.APP_DEMO_PROFILES`
(`acacia-hill`), `app` in `DEMO_PRODUCTS`, `SEED_APP_DEMO_MIN_AGENT` (1.7.0, not released yet).
- **Church export:** the `app` section (`exportAppSchema`: prayer wall rules, commitments as rules
with their skips, "I prayed" marks, campaigns, testimonies, prayer requests with their
moderation, emergency numbers, announcements, the church's own devotionals, simple events), and
`people[].roles` (optional) for a person with several roles.
- New samples: `devotionals-reply`, `messaging-get`, `messaging-get-reply`, `messaging-changed`,
`whatsapp-optout`, `whatsapp-optout-reply`, `church-export-app`. New JSON Schemas: `devotional`,
`devotionals-reply`, `messaging-get-reply`, `messaging-changed`, `whatsapp-optout-reply`.
## website@1.7.1 - 2026-11-28
Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only).
One migration: a nullable `framing` column on `Ministry`, `Leader` and `SimpleEvent`. Details in
`apps/website/CHANGELOG.md`.
## website@1.7.0 - 2026-11-27
Photos can be moved and zoomed in their frame, and unused photos deleted. Details in
`apps/website/CHANGELOG.md`. No migration.
- **Move and zoom:** a section's photo shows in its frame's shape for the template and layout,
with a dialog to drag and zoom it; saved with the section (`data.framing`), a draft until
published.
- **Delete photos:** the media library says where each photo is used, and deletes one used nowhere
(its files too); `DELETE /api/v1/admin/media/:id` refuses one in use.
## events@3.7.2 + website@1.6.1 - 2026-11-27
Events shown on the other product's site no longer show twice after a reseed, and the Website's
header marks the link to the Events site. Details in each app's CHANGELOG. No migrations.
- **Both:** the 15-minute event-feed poll and "Sync now" fetch the whole list and drop copies that
aren't in it, so events a sibling lost without listing them in `deleted` (a reseed, a restore)
can't stay beside the new ones. The fetch after an `event.changed` stays incremental.
- **Events 3.7.2:** new demo data (`set-demo.js`) lists the old events as removed in the feed,
publishes the new ones and tells the Website at once, and fetches the Website's events back in.
- **Website 1.6.1:** loading a demo lists the old events as removed and tells Events; the header
shows "Events site" with an external-link icon instead of a second "Events".
## website@1.6.0 - 2026-11-27
The demo church has real photos, and photos in small frames load at their size. Details in
`apps/website/CHANGELOG.md`. No migration.
- **Demo photos:** 104 Unsplash stock photos (models, free under the Unsplash License, credited
in `apps/website/backend/demo-photos/CREDITS.md`) instead of the generated illustration: a set
per demo profile, a portrait for every leader, a picture for each event, and a photo for each
message instead of the stand-in video's thumbnail. Loaded like uploads, in the responsive sizes.
- **Faster on phones:** the collage hero, the team's portraits and the ministry cards give the
browser their real width (`sizes`), so a phone no longer fetches the full-width photo for a
small frame.
## website@1.5.0 + crosscode script - 2026-11-27
The Church Website's nightly backup also backs up the photos and files. Details in
`apps/website/CHANGELOG.md`. No migration.
- **Website 1.5.0:** each night after the database, a snapshot of `backend/uploads` in
`backend/backups/uploads-YYYYMMDD-HHMMSS/`; unchanged files are hard links to the last snapshot,
so after the first full copy a night costs only the new files. On Admin → Backups, with its own
switch. Kept to the same count as the database backups.
- **crosscode script:** an uninstall keeps the Website's backups with `rsync -aH`, so the
snapshots' shared files stay shared instead of each becoming a full copy.
## website@1.4.0 - 2026-11-27
Database backups and background jobs for the Church Website, as Accounts and Cross Events have.
Details in `apps/website/CHANGELOG.md`. No migration (pg-boss makes its own `pgboss_website`
schema on first start).
- **Backups:** a gzipped `pg_dump` every night at 02:20 into `backend/backups/`, the same
`website-*.sql.gz` files the crosscode script makes before updates; Admin → Backups.
- **Background jobs** on pg-boss: the backup, the Hub heartbeat, the event feed and YouTube (before:
plain timers); Admin → Background jobs switches each on or off, changes its schedule, runs one now.
- **The heartbeat tells the Hub the truth:** the newest backup (before: always none, so the Hub
warned "No backup reported") and the real job mode and failures.
## contracts@1.19.0 + agent@1.6.0 + website@1.3.0 + crosscode script - 2026-11-27
Demo data for the Church Website, from the Hub (Hub 2.25.0). Additive: an Events `seed-demo` job
means what it did. Details in each app's CHANGELOG.md. No migrations.
- **contracts 1.19.0:** `agent.WEBSITE_DEMO_PROFILES` (eight, two per template:
`heritage-parish`, `heritage-city`, `bold-youth`, `bold-plant`, `community-family`,
`community-town`, `clean-modern`, `clean-campus`), `DEMO_PRODUCTS`, `DEMO_PROFILES_BY_PRODUCT`,
`SEED_WEBSITE_DEMO_MIN_AGENT` (1.6.0). `seed-demo` args take an optional `product` (`events`,
the default, or `website`); the profile must be one of that product's, and a Website demo takes
no `adminEmail`.
- **agent 1.6.0:** a Website `seed-demo` job runs `crosscode demo <church> website --profile <p>`.
- **website 1.3.0:** the eight demo churches (`backend/src/demo/seeds.ts`,
`npm run demo -- --profile <p>`, `--list`). They replace the content only: the church's profile
from Accounts, the site settings, the site icon and the admins stay, and the copy names the
church. `--template` alone is still the Acacia Hill development church.
- **crosscode script:** `crosscode demo <church> website --profile <p>`: backup, the demo as the
site's user (`--force`), reload, wait for `/api/health`. Refused on a Website release without
the profiles (before 1.3.0).
## accounts@1.8.0 + website@1.1.0 - 2026-11-26
The admins of both, redesigned as Cross Events' admin dashboard and settings. Details in each app's
+21 -12
View File
@@ -1,20 +1,26 @@
# Cross Code platform
The monorepo for the Cross Code products that come after Cross Events, and the formats they share.
The plan for every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where
things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
The monorepo for every Cross Code product except the Hub, and the formats they share. The plan for
every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where things
stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md), and the latest release of everything in
[`docs/VERSIONS.md`](./docs/VERSIONS.md).
| Folder | What | Status |
|--------|------|--------|
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including Cross Events and the Hub | Phase 0, in progress |
| `packages/ui` | `@crosscode/ui`: shared UI for the Website, App and Accounts | Placeholder, filled in during the Website phase |
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect) | Placeholder (phase 3) |
| `apps/website` | Church Website | Placeholder (phase 5) |
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
| `apps/events` | Cross Events (moved in from `joshua/hope-events` in 2.2.0) | Released and in use |
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect), the church profile | Released and in use |
| `apps/website` | Church Website | Released and in use (phase 5) |
| `apps/app` | Church App (PWA, House of Prayer) | Placeholder, being built (phase 6, [`docs/APP-1.0-PLAN.md`](./docs/APP-1.0-PLAN.md)) |
| `apps/agent` | The server agent: runs the Hub's signed jobs through the `crosscode` script | Released and in use |
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including the Hub | Released and in use |
| `packages/auth-client` | `@crosscode/auth-client`: how a product signs in through Accounts | In use |
| `packages/seo` | `@crosscode/seo`: JSON-LD and meta for every public site | In use |
| `packages/ui` | `@crosscode/ui`: fonts, brand style, `ChurchFooter` | In use |
| `packages/demo` | `@crosscode/demo`: the demo scenarios' churches, people and logos | In use (Accounts, Events, the Website) |
| `scripts/` | The `crosscode` script: install, deploy, demo, env, export, uninstall on the servers | In use (`main` is the release) |
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
([`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md)). Cross Code Hub (`joshua/events-hub`) stays in
its own repo and gets `@crosscode/contracts` as a packed release committed there (decision 22).
Cross Code Hub (`joshua/events-hub`) stays in its own repo and gets `@crosscode/contracts` as a
packed release committed there (decision 22).
## Docs
@@ -22,8 +28,11 @@ its own repo and gets `@crosscode/contracts` as a packed release committed there
|------|------|
| [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) | The plan: products, contracts, Accounts, sync, Hub, servers, build order, pricing, decisions |
| [`docs/HANDOVER.md`](./docs/HANDOVER.md) | Where each phase stands and what's next |
| [`docs/VERSIONS.md`](./docs/VERSIONS.md) | The latest release of everything, and what's deployed where |
| [`docs/hub-protocol.md`](./docs/hub-protocol.md) | Install ↔ Hub protocol, versions 1 and 2 (a copy lives in `events-hub`) |
| [`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md) | Phase 1b: Cross Events into the monorepo, the `crosscode` script |
| `docs/*-PLAN.md` | Each phase's plan and decisions (Events 2.2, 2.4, 3.0; Accounts 1.0; Agent 1.0; Website 1.0; App 1.0) |
| [`docs/ROLLOUT-1.0.md`](./docs/ROLLOUT-1.0.md) | The rollout checklist |
| [`docs/BIBLE-PERMISSIONS.md`](./docs/BIBLE-PERMISSIONS.md) | The Bible publishers' terms for the Church App's devotionals, the permission requests and their status |
## Rules (ROADMAP-v3 §1)
+64
View File
@@ -1,5 +1,69 @@
# Changelog — Accounts
## [1.10.0] - 2026-12-01
No migration, no new .env variables, no backend change. Needs `@crosscode/ui` 0.4.0 (built with
Accounts).
### Changed
- **Admin → Church profile:** the main and accent colours use the shared colour field
(`ColourField`, `@crosscode/ui` 0.4.0): a swatch, the hex code to type or paste, a preview, and a
message when the code isn't a colour, as Cross Events' Branding settings. Cross Events 3.9.0
now takes the church's name, logo, colours and contact details from this profile too.
## [1.9.0] - 2026-11-30
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
`crosscode` script on `main` builds it). **One migration** (`20261130000000_accounts_1_9`): two
columns on `Account`, one on `ProductLink`, a `WhatsAppOptOut` table. No new .env variables. Part of
Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
### Added
- **`messaging.get`** (contracts 1.20.0): a linked product gets the church's email (SMTP) and
WhatsApp (WAWP) settings, the password and token sealed with the link's secret, and is
remembered (`ProductLink.messagingWantedAt`). The reply is never kept in `ProductRequest`.
- **`messaging.changed`**: when an admin changes the email or WhatsApp settings here, or a product
saves them (`messaging.set`), each product that asked is sent the hint at
`/api/accounts/v1/messaging-changed` (a `Delivery`, retried as the other calls), except the one
that made the change.
- **The WhatsApp opt-out for every product** (APP-1.0-PLAN decision 11):
- `whatsapp.optout` from a product that received a STOP: the number is kept (`WhatsAppOptOut`),
every account with it is opted out (`Account.whatsappOptedOut`), its news on WhatsApp turned
off (a consent change, `whatsapp_stop`), and `user.updated` goes to every product with
`whatsapp_opted_out: true`. A number without an account is kept too: an account that gets it
later (sign-up, the account page, `people.ensure`, `people.update`, an import) starts opted out.
- **Accounts' own WAWP webhook**, `POST /api/v2/webhooks/whatsapp?secret=…`, for a church without
Cross Events: a STOP (English or Afrikaans: STOP, STOPP, UNSUBSCRIBE, OPT OUT, UITTEKEN) opts
the number out and answers once with how to undo it. Admin → Email and WhatsApp → **WhatsApp
replies (STOP)** shows the address to give WAWP and when it last called (or that Cross Events
takes the replies).
- Accounts sends an opted-out person no WhatsApp: sign-in codes go by email, setting WhatsApp up
as the two-step method is refused, sign-in notices skip it.
- **Turn WhatsApp back on** on the account page (Privacy), `POST /api/v2/me/whatsapp-on`: the
number's STOP is forgotten and the products are told. News on WhatsApp stays off until ticked.
- "Download my data" shows whether WhatsApp is off and since when.
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12), for demo sites only:
- `npm run demo -- --profile <scenario> --force` (`--list` for the eight), run by
`crosscode demo <church> accounts --profile <scenario>` after a backup. The church profile
becomes the scenario's church (name, short name, locale, colours, font pairing, corners,
campuses, service times, contact, social links), and `church.changed` goes to the products.
- Its **logo and icon**, drawn for the demo (`@crosscode/demo`), at
`/api/demo-assets/<scenario>/logo.svg` and `icon.svg`.
- Its **people** (54 to about 2 450, enough for the scenario's App band), at example.com with the
password `Demo@1234`, each with the same account id on every load and in every product
(`demoId`). Demo people from another scenario are anonymised; real people (any other address)
and Accounts admins are never touched; loading a scenario again brings its people back with
their ids.
### Checked on PostgreSQL 18
All three migrations on an empty database (the result matches the schema exactly); scenario loads
(Acacia Hill 0.8 s, Riverside's 2 457 people 3.4 s, switching back 14.7 s), the people's ids kept,
a real person untouched; the STOP opt-out, a known number on a new account, turning it back on;
`messaging.changed` queued; `npm run demo` with and without `--force`.
## [1.8.0] - 2026-11-26
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
+4
View File
@@ -16,6 +16,10 @@ sign-in settings, linked products and the church profile here.
- Roles stay in each product: Accounts only knows who someone is (plan §2, "Roles stay in each
product").
- Products sign in with `@crosscode/auth-client` (packages/auth-client).
- 1.9.0: the church's one set of email and WhatsApp settings for the App (`messaging.get`,
`messaging.changed`); the WhatsApp opt-out for every product (`src/accounts/whatsapp.ts`, its own
WAWP webhook in `src/links/whatsappWebhook.ts`); demo scenarios (`npm run demo -- --profile
<scenario> --force`, `src/demo/scenario.ts`, with `@crosscode/demo`; demo sites only).
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `ACCOUNTS_URL=http://localhost:3200`,
`LINKS_ALLOW_PRIVATE=true`), `npx prisma migrate deploy`, then `npm run dev` in both folders (the
+18
View File
@@ -3,6 +3,24 @@
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.10.0
- **An easier colour picker** in **Church profile**: pick your main and accent colours, or type or
paste their codes (like #1f4e79), and see them straight away.
- Your Events site (from version 3.9.0) now uses the name, logo, colours and contact details in
your church profile here, as your website does, so you change them in one place.
## 1.9.0
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
WhatsApp from any of your church's sites any more, reminders and sign-in codes included (codes
come by email instead). They can turn WhatsApp back on from their account page. Without Cross
Events, Admin → Email and WhatsApp shows the address to give WAWP, so the replies reach Accounts.
- Getting ready for the **Church App**: it will send with the email and WhatsApp settings you
already have, without asking for its own, and pick up any change you make here.
- **Demo churches** for Cross Code's demo sites: a church's name, logo, colours, service times and
people for each of eight demo scenarios. Never used on a real church's sign-in.
## 1.8.0
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.8.0",
"version": "1.10.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
@@ -14,10 +14,12 @@
"postinstall": "prisma generate",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status"
"prisma:status": "prisma migrate status",
"demo": "tsx scripts/demo.ts"
},
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/demo": "*",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
@@ -0,0 +1,20 @@
-- Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the WhatsApp opt-out for every product, and the
-- products that asked for the church's email and WhatsApp settings (messaging.get).
-- AlterTable
ALTER TABLE "Account" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "whatsappOptedOutAt" TIMESTAMP(3);
-- AlterTable
ALTER TABLE "ProductLink" ADD COLUMN "messagingWantedAt" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "WhatsAppOptOut" (
"phone" TEXT NOT NULL,
"keyword" TEXT NOT NULL,
"source" TEXT NOT NULL,
"receivedAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WhatsAppOptOut_pkey" PRIMARY KEY ("phone")
);
+30 -13
View File
@@ -58,6 +58,10 @@ model Account {
// 1.1.0: moved in from a product with 2FA but without recovery codes (Events keys its codes with
// its own secret, so they can't move): new ones are shown after the next sign-in's second step.
recoveryCodesNeeded Boolean @default(false)
// 1.9.0: replied STOP to the church's WhatsApp number (APP-1.0-PLAN §8): no product sends them
// WhatsApp until they turn it back on here. Sent to products as `whatsapp_opted_out`.
whatsappOptedOut Boolean @default(false)
whatsappOptedOutAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -201,20 +205,23 @@ model AppSetting {
// A linked product (Connect, crosscode.link/1). Each is also an OIDC client (§4): client_id is
// installId, the client secret is derived from `secret`, the addresses are fixed paths on `url`.
model ProductLink {
installId String @id
product String // events | website | app
url String
publicKey String
secret String // encrypted
connectedAt DateTime
connectedById String?
installId String @id
product String // events | website | app
url String
publicKey String
secret String // encrypted
connectedAt DateTime
connectedById String?
// 1.1.0: a move of this product's users into Accounts is under way (import.begin … finish).
importStartedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries Delivery[]
people ProductPerson[]
requests ProductRequest[]
importStartedAt DateTime?
// 1.9.0: asked for the church's email and WhatsApp settings (messaging.get), so it's sent
// messaging.changed when they change.
messagingWantedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries Delivery[]
people ProductPerson[]
requests ProductRequest[]
}
// 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it).
@@ -244,6 +251,16 @@ model ProductRequest {
@@index([createdAt])
}
// 1.9.0: numbers that replied STOP (APP-1.0-PLAN §8), kept with or without an account, so an
// account that gets the number later starts opted out. Removed when the person turns WhatsApp on.
model WhatsAppOptOut {
phone String @id // E.164
keyword String
source String // the product that received it, or "accounts" (its own webhook)
receivedAt DateTime
createdAt DateTime @default(now())
}
model LinkNonce {
nonce String @id
seenAt DateTime @default(now())
+50
View File
@@ -0,0 +1,50 @@
/**
* Loads a demo scenario's church and people into Accounts (1.9.0, docs/APP-1.0-PLAN.md §12).
*
* npm run demo -- --profile <scenario> [--scenario <scenario>] --force
* npm run demo -- --list
*
* It replaces the church profile and the demo people, so it needs --force. On a server,
* `crosscode demo <church> accounts --profile …` runs it (backup first), for the Hub's demo sites;
* Accounts loads first in a scenario, then Cross Events, the Website and the App.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { agent } from '@crosscode/contracts';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { loadConfig } from '../src/lib/config.js';
import { loadScenario } from '../src/demo/scenario.js';
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
return i > 0 ? process.argv[i + 1] : undefined;
};
if (process.argv.includes('--list')) {
for (const s of agent.DEMO_SCENARIOS) console.log(`${s.key.padEnd(18)} ${s.label}`);
process.exit(0);
}
const profile = agent.demoScenarioSchema.safeParse(arg('profile'));
if (!profile.success) {
console.error(`Usage: npm run demo -- --profile <scenario> --force (one of ${agent.DEMO_SCENARIO_KEYS.join(', ')}; --list)`);
process.exit(2);
}
const scenario = arg('scenario');
if (scenario !== undefined && scenario !== profile.data) {
console.error(`--scenario ${scenario} loads ${agent.demoScenario(agent.demoScenarioSchema.parse(scenario)).profiles.accounts} in Accounts, not ${profile.data}.`);
process.exit(2);
}
if (!process.argv.includes('--force')) {
console.error('This replaces the church profile and the demo people. Add --force to do it (demo sites only).');
process.exit(1);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const ctx = createCtx(loadConfig(), db);
try {
const r = await loadScenario(ctx, profile.data);
console.log(`${r.church} loaded: ${r.people} people (${r.created} new, ${r.updated} brought back, ${r.removed} from before removed). The linked products are told the church changed.`);
} finally {
await db.$disconnect();
}
@@ -44,6 +44,8 @@ export function profileOf(a: Account): Profile {
phone_number: a.phone,
phone_number_verified: a.phoneVerified,
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
// 1.9.0 (contracts 1.20.0): replied STOP; no product sends them WhatsApp.
whatsapp_opted_out: a.whatsappOptedOut,
};
}
@@ -112,7 +114,11 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
const what = purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
const text = `Your code to ${what} at ${churchName} is ${code}. It works for ${CODE_MINUTES} minutes. If you didn't ask for it, you can ignore this message.`;
if (method === 'whatsapp' && a.phone) {
// 1.9.0: someone who replied STOP gets no WhatsApp, codes included: email instead.
if (method === 'whatsapp' && a.phone && a.whatsappOptedOut && purpose !== 'sign_in') {
throw new SendError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page, or choose another way to get your codes.', 'CODE_NOT_SENT');
}
if (method === 'whatsapp' && a.phone && !a.whatsappOptedOut) {
try {
await ctx.messenger.whatsapp({ to: a.phone, text });
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
@@ -47,7 +47,7 @@ export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: str
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())) {
if (a.phone && a.phoneVerified && !a.whatsappOptedOut && (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';
@@ -42,6 +42,7 @@ export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?:
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) {
if (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
if (method === 'whatsapp' && a.whatsappOptedOut) throw new TwoFactorError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page first.', 'BAD_METHOD');
if (method === 'totp') {
const secret = generateSecret();
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
@@ -0,0 +1,71 @@
/**
* The WhatsApp opt-out for every product (1.9.0, docs/APP-1.0-PLAN.md §8, decision 11). A STOP to
* the church's WhatsApp number reaches Accounts (a product's `whatsapp.optout`, or Accounts' own
* webhook for a church without Events). Accounts keeps it: the number in `WhatsAppOptOut`, and
* `whatsappOptedOut` on each account with it. Every linked product is told (`user.updated` carries
* `whatsapp_opted_out`) and sends that person no WhatsApp of any kind until they turn it back on
* on their account page here. Accounts itself sends them none either (codes go by email).
*/
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
import { audit, loginEvent } from '../lib/audit.js';
import { profileChanged, setNewsConsent } from './service.js';
/** What counts as STOP in a reply (English and Afrikaans), as Cross Events reads it. */
export function isStopKeyword(text: unknown): boolean {
return /^\s*(stop|stopp|unsubscribe|stop all|opt out|optout|uitteken)\s*[.!]?\s*$/i.test(String(text ?? ''));
}
/** A WAWP chat id (`27821234567@c.us`) → `+27821234567`; null for groups, channels and LIDs. */
export function phoneFromChatId(chatId: unknown): string | null {
const m = /^(\d{8,15})@c\.us$/.exec(String(chatId ?? ''));
return m ? `+${m[1]}` : null;
}
/**
* A STOP from `phone` (E.164): keeps the number, opts out every account with it (news on WhatsApp
* off too) and tells the products. Returns how many accounts have the number.
*/
export async function optOutNumber(ctx: Ctx, phone: string, opts: { keyword: string; source: string; receivedAt: Date }): Promise<number> {
await ctx.db.whatsAppOptOut.upsert({
where: { phone },
update: { keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt },
create: { phone, keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt, createdAt: ctx.now() },
});
const accounts = await ctx.db.account.findMany({ where: { phone, status: { not: 'deleted' } } });
for (const a of accounts) await optOut(ctx, a, opts.source);
await audit(ctx, { actorId: null, actorRole: 'system', action: 'whatsapp_opt_out', targetType: 'phone', targetId: null, metadata: { source: opts.source, keyword: opts.keyword, accounts: accounts.length } });
return accounts.length;
}
async function optOut(ctx: Ctx, a: Account, source: string) {
if (!a.whatsappOptedOut) {
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: true, whatsappOptedOutAt: ctx.now() } });
await loginEvent(ctx, a.id, 'whatsapp_opted_out', undefined, { detail: { source } });
}
await setNewsConsent(ctx, a, { whatsapp: false }, 'whatsapp_stop');
await profileChanged(ctx, a.id);
}
/** The person turns WhatsApp back on (their account page): the number's STOP is forgotten too. */
export async function optBackIn(ctx: Ctx, a: Account): Promise<boolean> {
if (!a.whatsappOptedOut) return false;
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: false, whatsappOptedOutAt: null } });
if (a.phone) await ctx.db.whatsAppOptOut.deleteMany({ where: { phone: a.phone } });
await loginEvent(ctx, a.id, 'whatsapp_opted_in');
await profileChanged(ctx, a.id);
return true;
}
/**
* After an account's phone number is set or changed: a number that replied STOP starts opted out.
* (A number without a STOP never turns an opt-out off: only the person does.) Returns whether it did.
*/
export async function applyKnownOptOut(ctx: Ctx, accountId: string): Promise<boolean> {
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
if (!a?.phone || a.whatsappOptedOut) return false;
const stop = await ctx.db.whatsAppOptOut.findUnique({ where: { phone: a.phone } });
if (!stop) return false;
await optOut(ctx, a, 'known_number');
return true;
}
+11
View File
@@ -11,6 +11,8 @@ import { ApiError, handle, limit, sendError } from '../http.js';
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
import { messagingChanged, messagingParts } from '../links/messaging.js';
import { whatsappWebhookUrl } from '../links/whatsappWebhook.js';
import { currentSession } from '../oidc/sessions.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
@@ -195,6 +197,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
changed.push(key);
}
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
// 1.9.0: products sending with the church's settings (the App) fetch them again.
await messagingChanged(ctx, messagingParts(changed));
return { changed };
}));
@@ -209,6 +213,13 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
return { sent: true };
}));
// 1.9.0: WAWP's webhook address for STOP replies (a church without Cross Events points WAWP here).
r.get('/settings/whatsapp-webhook', handle(async (req, res) => {
await admin(req, res);
const linked = await ctx.db.productLink.findFirst({ where: { product: 'events' } });
return { ...(await whatsappWebhookUrl(ctx)), eventsLinked: !!linked };
}));
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
const me = await admin(req, res);
+4
View File
@@ -7,6 +7,7 @@
* /api/self/… the account page's own sign-in
* /api/church/v1, /api/links/v1/… for the church's other products
* /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0)
* /api/v2/webhooks/whatsapp WAWP's webhook: STOP replies (1.9.0)
* /api/v2/… the pages' API (sign-in steps, account, admin, setup)
*/
import express from 'express';
@@ -19,6 +20,7 @@ import { meRouter } from './me/routes.js';
import { LOGOUT_JS } from './oidc/pages.js';
import { publicRouter } from './public/routes.js';
import { requestsRouter } from './links/requests.js';
import { whatsappWebhookRouter } from './links/whatsappWebhook.js';
import { setupRouter } from './setup/routes.js';
import { health } from './hub/client.js';
import { appVersion } from './lib/version.js';
@@ -50,6 +52,8 @@ export function createApp(ctx: Ctx, provider: Provider) {
app.use('/api/self', selfRouter(ctx));
app.use('/api', requestsRouter(ctx, provider));
app.use('/api', publicRouter(ctx));
// 1.9.0: WAWP's webhook (STOP replies), before the pages' API: no same-origin check, its own secret.
app.use(whatsappWebhookRouter(ctx));
const v2 = express.Router();
v2.use(express.json({ limit: '64kb' }));
@@ -0,0 +1,94 @@
/**
* Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md §12, "Demo scenarios"): the
* scenario's church becomes the church profile (its own name, logo, icon, colours, campuses,
* service times and contact details), and its people get accounts. Loaded first, so Cross Events,
* the Website and the App then build their demo data around the same church and people.
*
* Only for demo sites (`crosscode demo <church> accounts --profile <scenario>`, which takes a backup
* first). People keep the same account id on every load (`demoId`), so products' copies still match.
* Demo people from before who aren't in this scenario are anonymised; real people (any address not at
* example.com) and Accounts admins are never touched.
*/
import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts';
import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo';
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import { hashPassword } from '../lib/passwords.js';
import { updateProfile } from '../church/profile.js';
import { currentNoticeVersion } from '../privacy/notice.js';
import { anonymise } from '../privacy/deletion.js';
/** Where Accounts serves the scenario's logo and icon (`/api/demo-assets/<scenario>/logo.svg`). */
export const DEMO_ASSETS_PATH = '/api/demo-assets';
const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const;
/** The SVG for a demo asset, or null for anything else. */
export function demoAsset(scenario: string, file: string): string | null {
const key = agent.demoScenarioSchema.safeParse(scenario);
const draw = (DEMO_ASSET_FILES as Record<string, (s: agent.DemoScenarioKey) => string>)[file];
return key.success && draw ? draw(key.data) : null;
}
export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number }
const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
const CHUNK = 500;
export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise<ScenarioResult> {
const { profile } = demoChurch(scenario);
const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`;
// The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed).
await updateProfile(ctx, {
name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale,
branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style },
campuses: profile.campuses, serviceTimes: profile.serviceTimes,
contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social,
});
// The people.
const people = demoPeople(scenario);
const wanted = new Set(people.map((p) => p.id));
const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a]));
let removed = 0;
for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) {
if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue;
await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } });
await anonymise(ctx, a.id);
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
removed++;
}
const passwordHash = await hashPassword(DEMO_PASSWORD);
const notice = await currentNoticeVersion(ctx);
const now = ctx.now();
const fields = (p: (typeof people)[number]) => ({
name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true,
phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const,
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now,
noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null,
whatsappOptedOut: false, whatsappOptedOutAt: null,
});
let updated = 0;
// Already here (this scenario loaded before, or anonymised when another was): brought back as they were.
for (const p of people) {
const a = existing.get(p.id);
if (!a) continue;
// Never take over a real person's account, nor an admin's.
if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue;
const other = await ctx.db.account.findUnique({ where: { email: p.email } });
if (other && other.id !== p.id) continue;
await ctx.db.account.update({ where: { id: p.id }, data: fields(p) });
updated++;
}
// New: in chunks, as the larger scenarios have a couple of thousand people.
const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email));
const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email));
for (let i = 0; i < fresh.length; i += CHUNK) {
await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) });
}
await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } });
await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() }));
return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed };
}
@@ -23,6 +23,7 @@ import { loginEvent } from '../lib/audit.js';
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
import { productName } from '../oidc/clients.js';
import { applyKnownOptOut } from '../accounts/whatsapp.js';
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
@@ -115,7 +116,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
}
if (stage === 'setup_two_factor') {
// Only the ways that can deliver a code now (1.2.0): an app always works.
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone && !a.whatsappOptedOut ? ['whatsapp'] : [])];
extra.why = a.role === 'admin' ? 'admin' : 'product';
}
if (stage === 'notice') {
@@ -177,6 +178,7 @@ export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<str
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
await loginEvent(ctx, a.id, 'account_created');
await applyKnownOptOut(ctx, a.id);
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
}
+2 -1
View File
@@ -19,7 +19,8 @@ export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole
export type LoginEventType =
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created';
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created'
| 'whatsapp_opted_out' | 'whatsapp_opted_in';
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
try {
+1 -1
View File
@@ -5,7 +5,7 @@
import type { Ctx } from '../context.js';
/** Encrypted at rest; never sent to the browser. */
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks', 'wawp_webhook_secret']);
/** The settings an admin may read and change through the generic settings API. */
export const ADMIN_SETTINGS = new Set([
@@ -1,12 +1,12 @@
/**
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, `church.changed` and (1.9.0) `messaging.changed`. Each is a
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
* export).
*/
import crypto from 'node:crypto';
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS, MESSAGING_CHANGED_PATH } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { callSibling, siblingUrl } from './http.js';
@@ -14,7 +14,10 @@ import { callSibling, siblingUrl } from './http.js';
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed' | 'messaging.changed';
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
@@ -23,7 +26,7 @@ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: str
for (const link of links) {
const callId = crypto.randomUUID();
made.push(await ctx.db.delivery.create({
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
data: { linkId: link.installId, callId, type, path: PATHS[type] ?? ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
}));
}
return made;
@@ -0,0 +1,31 @@
/**
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 4): one set of email and WhatsApp settings per church,
* kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the
* Church App) are sent `messaging.changed` when they change, so they fetch them again.
*/
import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { queueCall } from './deliveries.js';
/** The settings that make up the church's email and WhatsApp. */
const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']);
const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']);
/** Which parts the changed setting keys touch. */
export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } {
return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) };
}
/**
* Records the change and tells every product that asked for the settings, except the one that
* made the change (`exceptLinkId`, e.g. Events saving its own into Accounts).
*/
export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) {
if (!parts.email && !parts.whatsapp) return;
const at = ctx.now().toISOString();
await ctx.settings.set('messaging_updated_at', at);
const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } });
const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId);
if (!linkIds.length) return;
await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds });
}
+46 -3
View File
@@ -18,7 +18,7 @@ import {
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
} from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
import { LINK_HEADERS, openLinkValue, sealLinkValue, verify } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import type { ProductLink } from '../generated/prisma/client.js';
import { limit } from '../http.js';
@@ -32,6 +32,8 @@ 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';
import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js';
import { messagingChanged } from './messaging.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']);
@@ -134,6 +136,7 @@ async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportP
for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } });
await knows(ctx, link.installId, a.id, 'import', { upgrade: true });
await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } });
await applyKnownOptOut(ctx, a.id);
}
return { id: p.id, outcome: 'created', sub: p.id, reason: null };
}
@@ -225,6 +228,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
}
const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } });
await knows(ctx, link.installId, a.id, 'ensure');
await applyKnownOptOut(ctx, a.id);
const token = randomToken();
// Only the product's own address: never somewhere else.
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
@@ -259,7 +263,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
if (Object.keys(data).length) {
await ctx.db.account.update({ where: { id: a.id }, data });
if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } });
await profileChanged(ctx, a.id);
if (!(data.phone && (await applyKnownOptOut(ctx, a.id)))) await profileChanged(ctx, a.id);
}
await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) });
return reply({ ok: true as const });
@@ -323,6 +327,20 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
return reply({ people });
}
case 'messaging.get': {
// 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings,
// secrets sealed with the link's secret. The product is sent messaging.changed from now on.
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } });
const out = await messagingSettings(ctx, secret);
await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp });
return reply(out);
}
case 'whatsapp.optout': {
// 1.9.0 (decision 11): a STOP the product received. Kept here for every product.
const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) });
await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts });
return reply({ accounts });
}
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.
@@ -382,6 +400,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
}
}
if (save && (email?.saved || whatsapp?.saved)) await messagingChanged(ctx, { email: !!email?.saved, whatsapp: !!whatsapp?.saved }, link.installId);
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
const status = await messagingStatus(ctx);
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
@@ -419,7 +438,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.
// 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';
// messaging.get (1.9.0) carries sealed secrets: never kept either.
const isCheck = ('check' in request && request.check) || request.type === 'people.check' || request.type === 'messaging.get';
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(() => {});
}
@@ -465,6 +485,29 @@ async function messagingStatus(ctx: Ctx) {
};
}
/**
* messaging.get (1.9.0): what Accounts sends with (its saved settings, else the server's .env),
* the password and token sealed with the link's secret. A part that isn't set up is null.
*/
async function messagingSettings(ctx: Ctx, secret: string) {
const s = ctx.settings;
const host = (await s.get('smtp_host')) || ctx.config.smtp?.host || null;
const port = Number((await s.get('smtp_port')) || ctx.config.smtp?.port || 587);
const pass = (await s.get('smtp_pass')) || ctx.config.smtp?.pass || '';
const from = (await s.get('smtp_from')) || ctx.config.smtp?.from || '';
const email = host && from ? {
host, port,
secure: (await s.get('smtp_secure')) === 'true' || (ctx.config.smtp?.secure ?? port === 465),
user: (await s.get('smtp_user')) || ctx.config.smtp?.user || '',
pass: pass ? sealLinkValue(secret, pass) : null,
from,
} : null;
const token = (await s.get('wawp_access_token')) || ctx.config.wawp?.accessToken || null;
const instanceId = (await s.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null;
const whatsapp = token && instanceId ? { accessToken: sealLinkValue(secret, token), instanceId } : null;
return { email, whatsapp, updatedAt: (await s.get('messaging_updated_at')) || null };
}
/** Old remembered requests (the `cleanup` job). */
export async function forgetOldRequests(ctx: Ctx) {
return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } });
@@ -0,0 +1,68 @@
/**
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 11): Accounts takes WAWP's webhook itself, for a church
* without Cross Events (a WAWP number sends replies to one address; with Events, Events receives
* them and passes a STOP on with `whatsapp.optout`).
*
* POST /api/v2/webhooks/whatsapp?secret=… (WAWP's `message` event)
*
* WAWP doesn't sign webhooks, so the address carries a secret only Accounts and WAWP know
* (Admin → Email and WhatsApp shows it to paste into WAWP). Always answers 200 quickly, so WAWP
* never retries; only a STOP from a phone number is acted on.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import type { Ctx } from '../context.js';
import { isStopKeyword, optOutNumber, phoneFromChatId } from '../accounts/whatsapp.js';
export const WHATSAPP_WEBHOOK_PATH = '/api/v2/webhooks/whatsapp';
/** The secret in the webhook's address, made on first use. */
async function webhookSecret(ctx: Ctx): Promise<string> {
const saved = await ctx.settings.get('wawp_webhook_secret');
if (saved) return saved;
const secret = crypto.randomBytes(24).toString('base64url');
await ctx.settings.set('wawp_webhook_secret', secret);
return secret;
}
/** The address to paste into WAWP's webhook settings (event: message), and when it last called. */
export async function whatsappWebhookUrl(ctx: Ctx) {
return {
url: `${ctx.config.publicUrl.replace(/\/$/, '')}${WHATSAPP_WEBHOOK_PATH}?secret=${encodeURIComponent(await webhookSecret(ctx))}`,
lastSeenAt: await ctx.settings.get('wawp_webhook_last_seen'),
};
}
function secretMatches(given: string, secret: string) {
return given.length === secret.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(secret));
}
export async function handleWhatsappWebhook(ctx: Ctx, query: { secret?: unknown }, body: unknown): Promise<'ignored' | 'seen' | 'stopped'> {
const secret = await ctx.settings.get('wawp_webhook_secret');
if (!secret || !secretMatches(String(query.secret ?? ''), secret)) return 'ignored';
await ctx.settings.set('wawp_webhook_last_seen', ctx.now().toISOString());
const payload = ((body as { payload?: Record<string, unknown> })?.payload ?? {}) as { fromMe?: boolean; body?: unknown; from?: unknown };
if (payload.fromMe || !isStopKeyword(payload.body)) return 'seen';
const phone = phoneFromChatId(payload.from);
// Groups, channels and senders WhatsApp only names by a "LID" have no number to opt out.
if (!phone) return 'seen';
await optOutNumber(ctx, phone, { keyword: String(payload.body).trim().toUpperCase().slice(0, 40), source: 'accounts', receivedAt: ctx.now() });
// The one message after a STOP: what it did and how to undo it.
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'the church';
await ctx.messenger.whatsapp({ to: phone, text: `You won't get WhatsApp messages from ${church} any more. To turn them back on, go to ${ctx.config.publicUrl.replace(/\/$/, '')}/account.` })
.catch((e: Error) => console.warn('[whatsapp webhook] confirmation not sent:', e.message));
return 'stopped';
}
export function whatsappWebhookRouter(ctx: Ctx) {
const r = express.Router();
r.post(WHATSAPP_WEBHOOK_PATH, express.json({ limit: '256kb' }), async (req: Request, res: Response) => {
try {
await handleWhatsappWebhook(ctx, req.query as { secret?: unknown }, req.body);
} catch (e) {
console.error('[whatsapp webhook]', (e as Error).message);
}
res.json({ ok: true });
});
return r;
}
+14 -3
View File
@@ -18,6 +18,7 @@ import { requestExport } from '../privacy/export.js';
import { requestDeletion } from '../privacy/deletion.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { linkedProducts } from '../links/store.js';
import { applyKnownOptOut, optBackIn } from '../accounts/whatsapp.js';
/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */
const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' };
@@ -29,7 +30,9 @@ export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: numbe
return {
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified,
phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
// 1.9.0: replied STOP to the church's WhatsApp number; turned back on here.
whatsappOptedOut: a.whatsappOptedOut, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
};
}
@@ -80,7 +83,8 @@ export function meRouter(ctx: Ctx, provider: Provider) {
...(phone ? {} : { newsWhatsApp: false }),
},
});
await profileChanged(ctx, s.account.id);
// 1.9.0: a number that replied STOP starts opted out (which tells the products itself).
if (!(phone !== s.account.phone && (await applyKnownOptOut(ctx, s.account.id)))) await profileChanged(ctx, s.account.id);
return view(s);
}));
@@ -175,11 +179,18 @@ export function meRouter(ctx: Ctx, provider: Provider) {
r.put('/me/news', handle(async (req, res) => {
const s = await signedIn(req, res);
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page');
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone && !s.account.whatsappOptedOut }, 'account_page');
if (changed) await profileChanged(ctx, s.account.id);
return view(s);
}));
// 1.9.0: WhatsApp back on after a STOP (every product may send it again; news stays off until chosen).
r.post('/me/whatsapp-on', handle(async (req, res) => {
const s = await signedIn(req, res);
await optBackIn(ctx, s.account);
return view(s);
}));
r.get('/me/notice', handle(async (req, res) => {
await signedIn(req, res);
const n = await currentNotice(ctx);
+1 -1
View File
@@ -27,7 +27,7 @@ async function ownPart(ctx: Ctx, accountId: string) {
return {
product: 'accounts',
sections: [
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, whatsappOptedOut: a.whatsappOptedOut, whatsappOptedOutAt: a.whatsappOptedOutAt, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
@@ -10,6 +10,7 @@ import { branding, church } from '../church/profile.js';
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
import { setupNeeded } from '../setup/routes.js';
import { currentNotice } from '../privacy/notice.js';
import { DEMO_ASSETS_PATH, demoAsset } from '../demo/scenario.js';
const strip = (p: string) => p.replace(/^\/api/, '');
@@ -31,6 +32,14 @@ export function publicRouter(ctx: Ctx) {
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
}));
// 1.9.0: a demo scenario's logo and icon (drawn for the demo), which its church profile points at.
r.get(`${strip(DEMO_ASSETS_PATH)}/:scenario/:file`, limit(600), (req, res) => {
const svg = demoAsset(String(req.params.scenario), String(req.params.file));
if (!svg) return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such demo image.' } });
res.set({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'" });
return res.send(svg);
});
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
res.set('Cache-Control', 'public, max-age=60');
return church(ctx);
@@ -0,0 +1,92 @@
// Accounts 1.9.0: a demo scenario's church and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { CHURCH_PATHS, churchSchema } from '@crosscode/contracts';
import { demoPeople } from '@crosscode/demo';
import { startHarness, type Harness } from './support/harness.js';
import { loadScenario } from '../src/demo/scenario.js';
import { church } from '../src/church/profile.js';
import { verifyPassword } from '../src/lib/passwords.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
const live = async () => h.db.account.findMany({ where: { status: { not: 'deleted' } } });
describe('loading a demo scenario', () => {
test('the church becomes the scenario\'s, with its own logo and icon, and the products are told', async () => {
const real = await h.makeAccount({ email: 'office@hope.test' });
const admin = await h.makeAccount({ email: 'admin.demo@example.com', role: 'admin' });
const r = await loadScenario(h.ctx, 'community-family');
assert.equal(r.church, 'Acacia Hill Church');
const c = await church(h.ctx);
assert.ok(churchSchema.safeParse(c).success);
assert.equal(c.name, 'Acacia Hill Church');
assert.equal(c.shortName, 'Acacia Hill');
assert.equal(c.branding.colours.primary, '#2f6f4f');
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'soft' });
assert.equal(c.branding.logoUrl, `${h.publicUrl}/api/demo-assets/community-family/logo.svg`);
assert.equal(c.contact.email, 'office.acaciahill@example.com');
assert.ok((await h.db.delivery.findMany({ where: { type: 'church.changed' } })).length >= 1);
// Real people and admins are never touched.
assert.equal((await h.db.account.findUnique({ where: { id: real.id } }))!.status, 'active');
assert.equal((await h.db.account.findUnique({ where: { id: admin.id } }))!.status, 'active');
});
test('every person has an account with the id the other products work out, and the demo password', async () => {
const people = demoPeople('community-family');
const ids = new Set((await live()).map((a) => a.id));
for (const p of people) assert.ok(ids.has(p.id), p.email);
const pastor = (await h.db.account.findUnique({ where: { id: people[0]!.id } }))!;
assert.equal(pastor.name, 'Thabo Nkosi');
assert.equal(pastor.emailVerified, true);
assert.ok(await verifyPassword('Demo@1234', pastor.passwordHash as string));
});
test('loading it again changes nobody\'s id', async () => {
const r = await loadScenario(h.ctx, 'community-family');
assert.equal(r.created, 0);
assert.equal(r.removed, 0);
assert.equal(r.updated, demoPeople('community-family').length);
});
test('another scenario replaces the demo people; switching back brings them back with the same ids', async () => {
const before = demoPeople('community-family');
const r = await loadScenario(h.ctx, 'bold-plant');
assert.equal(r.church, 'Harbour City Church');
assert.equal(r.removed, before.length);
assert.equal(r.created, demoPeople('bold-plant').length);
assert.equal((await h.db.account.findUnique({ where: { id: before[0]!.id } }))!.status, 'deleted');
assert.ok(await h.db.account.findUnique({ where: { email: 'office@hope.test' } }), 'a real person stays');
assert.equal((await h.db.account.findUnique({ where: { email: 'admin.demo@example.com' } }))!.status, 'active', 'an admin stays');
const back = await loadScenario(h.ctx, 'community-family');
assert.equal(back.updated, before.length);
const pastor = (await h.db.account.findUnique({ where: { id: before[0]!.id } }))!;
assert.equal(pastor.status, 'active');
assert.equal(pastor.email, before[0]!.email);
});
test('a scenario with campuses has them in the profile', async () => {
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church' }));
// Riverside has about 2 450 people; only its profile is checked here.
const c = await (async () => { await loadScenario(h.ctx, 'clean-campus'); return church(h.ctx); })();
assert.deepEqual(c.campuses.map((x) => x.slug), ['stellenbosch', 'paarl', 'somerset-west']);
assert.equal(c.serviceTimes.filter((s) => s.campus === 'stellenbosch').length, 2);
});
});
describe('demo logos', () => {
test('served as SVG for a scenario, 404 for anything else', async () => {
const res = await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/icon.svg`);
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/svg+xml; charset=utf-8');
assert.match(await res.text(), /^<svg[^>]*>.*#e4572e/);
const logo = await (await fetch(`${h.publicUrl}/api/demo-assets/heritage-parish/logo.svg`)).text();
assert.match(logo, /St Columba&apos;s Church/);
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/nowhere/icon.svg`)).status, 404);
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/secrets.txt`)).status, 404);
assert.equal((await fetch(`${h.publicUrl}${CHURCH_PATHS.profile}`)).status, 200);
});
});
@@ -12,7 +12,7 @@ const DEFAULTS: Record<string, () => Row> = {
account: () => ({
givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active',
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0,
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false,
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, whatsappOptedOut: false, whatsappOptedOutAt: null,
}),
recoveryCode: () => ({ usedAt: null }),
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
@@ -20,13 +20,13 @@ const DEFAULTS: Record<string, () => Row> = {
loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }),
privacyNotice: () => ({ publishedById: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
productLink: () => ({ connectedById: null, importStartedAt: null }),
productLink: () => ({ connectedById: null, importStartedAt: null, messagingWantedAt: null }),
oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }),
delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }),
dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }),
deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' };
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId', whatsAppOptOut: 'phone' };
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
@@ -117,6 +117,10 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
table().set(row[key], row);
return clone(row);
},
createMany: async ({ data }: { data: Row[] }) => {
for (const d of data) await api.create({ data: d });
return { count: data.length };
},
update: async ({ where, data }: { where: Row; data: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
@@ -0,0 +1,195 @@
// Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the church's email and WhatsApp settings for a product
// that sends with them (messaging.get, messaging.changed), and the WhatsApp opt-out for every
// product (whatsapp.optout, Accounts' own WAWP webhook, turning WhatsApp back on).
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { after, before, beforeEach, describe, test } from 'node:test';
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH, messagingChangedSchema, messagingGetReplySchema, userUpdatedSchema } from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, signedHeaders } from '@crosscode/contracts/signing';
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
import { runDue } from '../src/links/deliveries.js';
import { messagingChanged } from '../src/links/messaging.js';
import { handleWhatsappWebhook, whatsappWebhookUrl } from '../src/links/whatsappWebhook.js';
import { isStopKeyword, phoneFromChatId } from '../src/accounts/whatsapp.js';
let h: Harness;
let messenger: MemoryMessenger;
before(async () => { h = await startHarness(); messenger = h.messenger as MemoryMessenger; });
after(async () => { await h.close(); });
beforeEach(async () => {
h.received.length = 0;
messenger.whatsappOn = true;
messenger.whatsapps.length = 0;
await h.db.delivery.deleteMany({});
});
/** A request from the harness's linked product (signed with its link's secret). */
async function ask(body: Record<string, unknown>) {
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: PRODUCT_ID, secret: h.linkSecret, rawBody: raw }) } });
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
}
const sent = (path: string) => h.received.filter((r) => r.path === path).map((r) => JSON.parse(r.body) as Record<string, unknown>);
describe('messaging.get', () => {
test('nothing set up: both parts null', async () => {
const r = await ask({ type: 'messaging.get' });
assert.equal(r.status, 200, JSON.stringify(r.body));
assert.ok(messagingGetReplySchema.safeParse(r.body).success);
assert.equal(r.body.email, null);
assert.equal(r.body.whatsapp, null);
});
test('gives the settings with the password and token sealed for this link only, and never keeps the reply', async () => {
await h.ctx.settings.setMany({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_user: 'hello@hope.test', smtp_pass: 'mail-pass', smtp_from: 'hello@hope.test', wawp_access_token: 'wa-token', wawp_instance_id: 'HOPE01' });
const r = await ask({ type: 'messaging.get' });
assert.equal(r.status, 200, JSON.stringify(r.body));
const reply = messagingGetReplySchema.parse(r.body);
assert.equal(reply.email?.host, 'smtp.hope.test');
assert.equal(reply.email?.user, 'hello@hope.test');
assert.notEqual(reply.email?.pass, 'mail-pass');
assert.equal(openLinkValue(h.linkSecret, reply.email!.pass!), 'mail-pass');
assert.equal(openLinkValue(h.linkSecret, reply.whatsapp!.accessToken), 'wa-token');
assert.equal(reply.whatsapp?.instanceId, 'HOPE01');
assert.doesNotMatch(JSON.stringify(r.body), /mail-pass|wa-token/);
const link = await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } });
assert.ok(link?.messagingWantedAt, 'remembered as wanting messaging.changed');
assert.equal((await h.db.productRequest.findMany({ where: { type: 'messaging.get' } })).length, 0);
});
});
describe('messaging.changed', () => {
test('an admin changing WhatsApp tells the products that asked', async () => {
await ask({ type: 'messaging.get' });
await messagingChanged(h.ctx, { email: false, whatsapp: true });
await runDue(h.ctx);
const calls = sent(MESSAGING_CHANGED_PATH);
assert.equal(calls.length, 1);
assert.ok(messagingChangedSchema.safeParse(calls[0]).success);
assert.equal(calls[0]!.whatsapp, true);
assert.equal(calls[0]!.email, false);
assert.ok(h.received.find((x) => x.path === MESSAGING_CHANGED_PATH && h.signedByLink(x)), 'signed with the link');
assert.ok(await h.ctx.settings.get('messaging_updated_at'));
});
test('not to the product that made the change, nor for unrelated settings', async () => {
await ask({ type: 'messaging.get' });
await messagingChanged(h.ctx, { email: true, whatsapp: false }, PRODUCT_ID);
await messagingChanged(h.ctx, { email: false, whatsapp: false });
await runDue(h.ctx);
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
});
test('a product that never asked isn\'t told', async () => {
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { messagingWantedAt: null } });
await messagingChanged(h.ctx, { email: true, whatsapp: true });
await runDue(h.ctx);
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
});
});
describe('whatsapp.optout', () => {
test('opts out every account with the number, turns WhatsApp news off and tells the products', async () => {
const a = await h.makeAccount({ email: 'stop1@hope.test', phone: '+27825550001', phoneVerified: true, newsWhatsApp: true });
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550001', receivedAt: new Date().toISOString(), keyword: 'STOP' });
assert.equal(r.status, 200, JSON.stringify(r.body));
assert.equal(r.body.accounts, 1);
const after = (await h.db.account.findUnique({ where: { id: a.id } }))!;
assert.equal(after.whatsappOptedOut, true);
assert.equal(after.newsWhatsApp, false);
await runDue(h.ctx);
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).find((b) => b.type === 'user.updated' && b.sub === a.id);
assert.ok(updated, 'user.updated sent');
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, true);
});
test('keeps a number without an account: an account made with it later starts opted out', async () => {
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550002', receivedAt: new Date().toISOString(), keyword: 'STOP' });
assert.equal(r.body.accounts, 0);
const ensured = await ask({ type: 'people.ensure', name: 'Later Person', email: 'later@hope.test', phone: '+27825550002', returnUrl: `${h.productUrl}/` });
assert.equal(ensured.status, 200, JSON.stringify(ensured.body));
const a = (await h.db.account.findUnique({ where: { id: ensured.body.sub as string } }))!;
assert.equal(a.whatsappOptedOut, true);
});
test('a code for someone who replied STOP goes by email, never WhatsApp', async () => {
await h.makeAccount({ email: 'stop3@hope.test', password: 'Correct-horse-1', phone: '+27825550003', twoFactorMethod: 'whatsapp', whatsappOptedOut: true });
const r = await h.signIn(new Browser(), 'stop3@hope.test', 'Correct-horse-1');
assert.ok('pending' in r);
assert.equal(r.pending.stage, 'two_factor');
assert.match(String(r.pending.sentTo), /@hope\.test$/);
assert.equal(messenger.whatsapps.filter((w) => w.to === '+27825550003').length, 0);
});
});
describe('Accounts\' own WAWP webhook', () => {
const message = (from: string, body: string, fromMe = false) => ({ event: 'message', payload: { from, body, fromMe } });
test('reads STOP and phone numbers as Cross Events does', () => {
for (const s of ['STOP', ' stop ', 'Stop!', 'unsubscribe', 'STOPP', 'opt out']) assert.ok(isStopKeyword(s), s);
for (const s of ['stop the music', 'please stop', '', 'STOPPED']) assert.ok(!isStopKeyword(s), s);
assert.equal(phoneFromChatId('27825550004@c.us'), '+27825550004');
assert.equal(phoneFromChatId('1234567890-123@g.us'), null);
assert.equal(phoneFromChatId('12345@lid'), null);
});
test('ignores a call without the secret', async () => {
const { url } = await whatsappWebhookUrl(h.ctx);
assert.match(url, /\/api\/v2\/webhooks\/whatsapp\?secret=/);
await h.makeAccount({ email: 'stop4@hope.test', phone: '+27825550004' });
assert.equal(await handleWhatsappWebhook(h.ctx, { secret: 'wrong' }, message('27825550004@c.us', 'STOP')), 'ignored');
const res = await fetch(`${h.publicUrl}/api/v2/webhooks/whatsapp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550004@c.us', 'STOP')) });
assert.equal(res.status, 200);
assert.equal((await h.db.account.findUnique({ where: { email: 'stop4@hope.test' } }))!.whatsappOptedOut, false);
});
test('a STOP through the real address opts the number out and answers once', async () => {
const { url } = await whatsappWebhookUrl(h.ctx);
await h.makeAccount({ email: 'stop5@hope.test', phone: '+27825550005' });
const path = url.slice(url.indexOf('/api/'));
const res = await fetch(`${h.publicUrl}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550005@c.us', 'Stop')) });
assert.equal(res.status, 200);
assert.equal((await h.db.account.findUnique({ where: { email: 'stop5@hope.test' } }))!.whatsappOptedOut, true);
assert.ok(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550005' } }));
const replies = messenger.whatsapps.filter((w) => w.to === '+27825550005');
assert.equal(replies.length, 1);
assert.match(replies[0]!.text, /won't get WhatsApp messages from Hope Family Church/);
assert.ok((await whatsappWebhookUrl(h.ctx)).lastSeenAt);
});
test('other messages, and the church\'s own, change nothing', async () => {
const { url } = await whatsappWebhookUrl(h.ctx);
const secret = new URL(url).searchParams.get('secret');
await h.makeAccount({ email: 'stop6@hope.test', phone: '+27825550006' });
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'Thanks!')), 'seen');
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'STOP', true)), 'seen');
assert.equal((await h.db.account.findUnique({ where: { email: 'stop6@hope.test' } }))!.whatsappOptedOut, false);
});
});
describe('turning WhatsApp back on', () => {
test('on the account page: every product may send it again, and the number\'s STOP is forgotten', async () => {
await ask({ type: 'whatsapp.optout', phone: '+27825550007', receivedAt: new Date().toISOString(), keyword: 'STOP' });
const a = await h.makeAccount({ email: 'stop7@hope.test', password: 'Correct-horse-1', phone: '+27825550007', whatsappOptedOut: true, whatsappOptedOutAt: new Date() });
const browser = new Browser();
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'stop7@hope.test', password: 'Correct-horse-1' });
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
const me = await h.api(browser, 'GET', '/api/v2/me');
assert.equal(me.body.whatsappOptedOut, true);
// News on WhatsApp can't be ticked while it's off.
await h.api(browser, 'PUT', '/api/v2/me/news', { email: false, whatsapp: true });
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.newsWhatsApp, false);
const on = await h.api(browser, 'POST', '/api/v2/me/whatsapp-on');
assert.equal(on.status, 200, JSON.stringify(on.body));
assert.equal(on.body.whatsappOptedOut, false);
assert.equal(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550007' } }), null);
await runDue(h.ctx);
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).filter((b) => b.type === 'user.updated' && b.sub === a.id).at(-1);
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, false);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.8.0",
"version": "1.10.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
@@ -14,6 +14,7 @@ import { useExternalEffect } from "@/lib/hooks";
type Me = {
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
whatsappOptedOut?: boolean;
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
};
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
@@ -24,6 +25,7 @@ const EVENT: Record<string, string> = {
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
whatsapp_opted_out: "WhatsApp turned off (replied STOP)", whatsapp_opted_in: "WhatsApp turned back on",
};
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
@@ -291,8 +293,17 @@ function Privacy({ me, onDone, onFail }: Props) {
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
}}>
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone || me.whatsappOptedOut} hint={!me.phone ? "Add your mobile number first." : me.whatsappOptedOut ? "WhatsApp is off: see below." : undefined} />
</form>
{me.whatsappOptedOut && (
<div className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm">
<p className="mb-2">You replied STOP to the church&apos;s WhatsApp number, so none of the church&apos;s sites send you WhatsApp messages (reminders and codes come by email instead).</p>
<Button variant="secondary" onClick={async () => {
const r = await call("POST", "/me/whatsapp-on");
if (r.ok) onDone("WhatsApp is back on. Church news on WhatsApp stays off until you tick it."); else onFail(r.error.message);
}}>Turn WhatsApp back on</Button>
</div>
)}
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
<div className="border-t pt-4">
+33 -5
View File
@@ -6,7 +6,7 @@ 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 { Button, Checkbox, ColourField, Field, Notice } from "@crosscode/ui";
import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText";
import { Card, Heading } from "@/components/Panel";
@@ -71,6 +71,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
{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"]} />
<WhatsAppReplies />
</>}
{section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />}
@@ -324,6 +325,8 @@ type ChurchData = { name: string; shortName: string | null; branding: { logoUrl:
function Church({ flash }: { flash: Flash }) {
const [c, setC] = useState<ChurchData | null>(null);
const [fields, setFields] = useState<Record<string, string>>({});
// The two colours as typed (ColourField is controlled); the saved ones until changed.
const [colours, setColours] = useState<{ primary?: string; accent?: string }>({});
useExternalEffect(() => {
let alive = true;
call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); });
@@ -343,14 +346,16 @@ function Church({ flash }: { flash: Flash }) {
branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } },
contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) },
});
if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); }
if (r.ok) { setC(r.data); setFields({}); setColours({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); }
}}>
<Field label="Name" name="name" defaultValue={c.name} required error={fields.name} />
<Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} />
<Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} />
<div className="grid grid-cols-2 gap-4">
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} />
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} />
<div className="grid gap-4 sm:grid-cols-2">
<ColourField label="Main colour" name="primary" value={colours.primary ?? c.branding.colours.primary} onChange={(primary) => setColours((x) => ({ ...x, primary }))}
hint="Buttons, links and headings on every site." error={fields["branding.colours.primary"]} />
<ColourField label="Accent colour" name="accent" value={colours.accent ?? c.branding.colours.accent ?? "#f2a900"} onChange={(accent) => setColours((x) => ({ ...x, accent }))}
hint="Highlights and touches beside the main colour." error={fields["branding.colours.accent"]} />
</div>
<Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} />
<Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} />
@@ -446,6 +451,29 @@ function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: strin
);
}
/** 1.9.0: where WAWP sends replies, so a STOP reaches Accounts (only needed without Cross Events). */
function WhatsAppReplies() {
const [data, setData] = useState<{ url: string; lastSeenAt: string | null; eventsLinked: boolean } | null>(null);
useExternalEffect(() => {
let alive = true;
call<{ url: string; lastSeenAt: string | null; eventsLinked: boolean }>("GET", "/admin/settings/whatsapp-webhook").then((r) => { if (alive && r.ok) setData(r.data); });
return () => { alive = false; };
}, []);
if (!data) return null;
return (
<Card>
<Heading icon={<MessageCircle className="h-4 w-4" />} sub="Someone who replies STOP to the church's WhatsApp number gets no WhatsApp from any of the church's sites until they turn it back on on their account page.">WhatsApp replies (STOP)</Heading>
{data.eventsLinked
? <p className="text-sm text-gray-600">Cross Events receives the replies and passes a STOP on to Accounts. Keep WAWP&apos;s webhook pointing at Cross Events.</p>
: <>
<p className="mb-2 text-sm text-gray-600">In WAWP, set the webhook (event: message) to this address:</p>
<input readOnly className="mb-2 w-full rounded border bg-gray-50 px-2 py-1 font-mono text-xs" value={data.url} onFocus={(e) => e.currentTarget.select()} aria-label="Webhook address" />
<p className="text-sm text-gray-600">{data.lastSeenAt ? `Last message received: ${new Date(data.lastSeenAt).toLocaleString("en-ZA")}.` : "No message received through it yet."}</p>
</>}
</Card>
);
}
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
type NoticeVersion = { version: number; title: string; body: string };
+16
View File
@@ -13,6 +13,22 @@ Write for the person updating servers: what the agent can now do from the Hub, a
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.7.0
- **Demo scenarios.** The Hub (2.26.0 and later) can load a whole demo church on a demo client:
Accounts first, then Cross Events, the Website and the App, the same church and people in each.
It's one job: the server loads **whatever the client has installed** and skips the rest, so a
client with only Accounts and the Website gets both. Every product's release is checked first
(Accounts 1.9.0, Events 3.8.0, Website 1.8.0); if one fails part-way, the report says which
products are out of step. The agent also runs single demo jobs for Accounts and (from App
1.0.0) the Church App. Single-product demo data works as before.
## 1.6.0
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
eight demo churches on a demo site, as it already could for Cross Events. Needs Website 1.3.0 on
the site. Cross Events' demo data works as before.
## 1.5.0
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.5.0",
"version": "1.7.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",
+14 -2
View File
@@ -58,8 +58,20 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
if (job.args.restart) out.push("--restart");
return out;
}
case "seed-demo":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "seed-demo": {
// 1.6.0: the Website's demo names the product; Events' (no product) keeps its old form.
// 1.7.0: the App's and Accounts' too, and a demo scenario passed on (`--scenario`), so each
// product can tell a scenario load from a single one.
const a = job.args;
const product = a.product && a.product !== "events" ? [a.product] : [];
return ["demo", a.church, ...product, "--profile", a.profile,
...(a.scenario ? ["--scenario", a.scenario] : []),
...(a.adminEmail ? ["--admin-email", a.adminEmail] : [])];
}
case "seed-scenario":
// 1.7.0: a whole demo scenario. No product named: the script loads every product the church
// has on this server, Accounts first, and skips the others.
return ["demo", job.args.church, "--scenario", job.args.scenario, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
+1 -1
View File
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.5.0";
export const AGENT_VERSION = "1.7.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+23
View File
@@ -47,6 +47,29 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
// 1.6.0: the Website's demo.
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant" } }))).toEqual(["demo", "hope", "website", "--profile", "bold-plant"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
});
it("seed-scenario 1.7.0: one job, no product named, so the server seeds whatever the church has", () => {
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "community-family" } }))).toEqual(["demo", "demo2", "--scenario", "community-family"]);
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "demo2", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
expect(() => parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", products: ["website"] } })).toThrow();
});
it("seed-demo 1.7.0: the App's and Accounts' demos, and a scenario passed on to every product", () => {
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "app", profile: "community-family" } }))).toEqual(["demo", "hope", "app", "--profile", "community-family"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "accounts", profile: "bold-youth", scenario: "bold-youth" } })))
.toEqual(["demo", "hope", "accounts", "--profile", "bold-youth", "--scenario", "bold-youth"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "clean-campus", scenario: "clean-campus" } })))
.toEqual(["demo", "hope", "website", "--profile", "clean-campus", "--scenario", "clean-campus"]);
// Events keeps its old form (no product), with the scenario and the admin kept.
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "bold-youth", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "hope", "--profile", "bold-youth", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
// A scenario's profile must be the scenario's for that product (the contracts refuse the job).
expect(() => parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant", scenario: "bold-youth" } })).toThrow();
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
+82
View File
@@ -5,6 +5,88 @@ 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.9.0] - 2026-12-01
No migration, no new settings or environment variables. One new dependency: `svg-to-pdfkit`
0.1.8 (MIT, pure JavaScript; draws SVG logos in PDFs). Works with any Accounts; nothing changes on
a site without Accounts.
### Fixed
- **The church's details come from Accounts.** The church profile set only the fonts, corners and
footer, so after a change in Accounts (or a demo scenario loaded on a new church) Events kept its
own old name, logo and colours while the Website showed the new ones. Now, while Accounts is
connected, the profile's name, logo, icon, main and accent colours, email, phone and address win
over `org_name`, `logo_url`, `favicon_url`, `primary_color`, `accent_color`, `org_email`,
`org_phone` and `org_address` everywhere: the public settings (`GET /api/v2/settings`), and
everything that reads the settings cache (emails, WhatsApp, PDFs, 2FA labels). Only what the
profile has: no icon or accent there keeps this site's own. `org_tagline` and `secondary_color`
stay this site's (`src/accounts/church.ts` `churchSettings`, `utils/settingsCache.js`
`setAccountsOverrides`). `church.changed` fetches the profile straight away; disconnecting
Accounts brings the site's own back. The look sent to Accounts on a move stays this site's own
(`getStoredSetting`).
- **PDFs with the church's logo from Accounts.** Tickets, invoices, receipts, certificates and
privacy exports could only draw a logo uploaded here. The logo from Accounts is copied into
`uploads/accounts` (once per address, when the profile arrives or the first PDF needs it; old
copies removed; 2 MB at most; `utils/logoCopy.js`). PNG and JPEG are drawn as pictures and SVG
(the demo churches' logos, and an SVG uploaded here) as shapes with `svg-to-pdfkit`
(`drawLogo`); an SVG never opens a file or address it names. WebP and GIF show the name only.
- A logo address on another `localhost` port (Accounts in development) is no longer rewritten to
the API's address; only this site's own uploads are (`resolveToApiOrigin`).
### Changed
- **Settings → Organisation and Branding** show the fields Accounts sets read-only, with a link to
the church profile in Accounts, and never send them back (`GET /api/v2/settings/all` adds
`accounts_managed`, the keys Accounts sets, with Accounts' values).
## [3.8.0] - 2026-11-30
Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on
`main` builds it). **One migration** (`20261130120000_whatsapp_stop`): `User.whatsappOptedOut` and a
`WhatsAppStop` table. No new settings. Works with any Accounts; the opt-out reaches the church's
other products with Accounts 1.9.0. Part of Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
### Changed
- **STOP stops all WhatsApp** (APP-1.0-PLAN decision 11), not only news: event updates, tickets,
kids check-in messages and two-step codes too (codes go by email). Checked before every message
(`sendText`, `sendPdf`, `src/utils/whatsappStop.js`), against the numbers that replied STOP here
(`WhatsAppStop`) and the accounts Accounts says opted out (`User.whatsappOptedOut`, from
`user.updated`'s `whatsapp_opted_out`). News on WhatsApp is turned off as before.
- **A STOP received here is passed on to Accounts** (`whatsapp.optout`, contracts 1.20.0), which
keeps it for every product. The reply says how to undo it: the account page in Accounts, or,
without Accounts, reply START (which turns it back on here). With Accounts, START only answers
with the account page; turned back on there, `user.updated` clears this site's STOP for the
number too. STOPP and UITTEKEN (Afrikaans) count as STOP.
### Added
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12): `set-demo.js --profile=<scenario>` for
the eight (heritage-parish … clean-campus), each built as one of the four kinds of demo but around
the scenario's church from `@crosscode/demo`: its people (the same as in Accounts, the Website and
the App; leads become the demo staff and event contacts), and its own campuses with people at
their home campus. Accounts' part loads first; the demo then links its people to their accounts
and never removes them (`people.removeDemo` skips the scenario's own). A small church's events
sell to the people it has (the breakfast isn't sold out at St Columba's). The four demos as before.
## [3.7.2] - 2026-11-27
No migrations, no new settings.
### Fixed
- **New demo data no longer leaves the old events on the church's Website.** `set-demo.js`
truncated `FeedEntry`, so the feed never listed the old events in `deleted` and the Website kept
showing them beside the new ones. Now `FeedEntry` is kept and its live entries are marked removed,
the links' `lastGoodAt` is reset (their copies were truncated, so the next fetch is a full one),
and after loading the script publishes the new events, sends `event.changed` to the linked
products and fetches their events back in (`demoFeed`), so the Website's next page load is right.
- **Copies of a linked product's events can't stay forever.** The 15-minute `feed-sync` job and
"Sync now" fetch the whole list and drop copies that aren't in it (`syncLink(link, now, { full: true })`),
so events a sibling lost without listing them in `deleted` (a reseed, a restore) go within 15
minutes. The fetch after an `event.changed` still asks only for what changed.
## [3.7.1] - 2026-11-26
No migrations, no new settings.
+5 -2
View File
@@ -765,8 +765,11 @@ registered for; always sent) or **News & announcements** (only to people who opt
on that channel and haven't unsubscribed). News emails carry an unsubscribe link and
one-click `List-Unsubscribe` headers; news WhatsApps end with "Reply STOP" and a link.
Event updates say why they were sent and link to the preferences. A STOP reply on
WhatsApp turns off WhatsApp news (through WAWP's `message` webhook, checked against a
secret in the webhook URL).
WhatsApp (through WAWP's `message` webhook, checked against a secret in the webhook URL)
**stops every WhatsApp message to that number** from 3.8.0, event updates, tickets and
codes included (they go by email), and from the church's other sites too: it's passed on
to the church's Accounts, where the person turns WhatsApp back on (without Accounts, by
replying START).
**Privacy notice** (`/legal/privacy`) — edited in **Admin → Privacy (POPIA)**
(`/dashboard/admin/privacy`): sections start from the built-in text; drafts, preview,
+28
View File
@@ -12,6 +12,34 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 3.9.0
- **Your church's name, logo, colours and contact details now come from your church profile in
Accounts**, as they do on your website. Change them once in Accounts and your Events site shows
the change within moments, in its pages, emails and WhatsApp messages too. Before, Events kept
the details it had been given when it was set up.
- In **Site settings → Organisation and Branding**, those details are shown but can't be changed
there any more; a link takes you to your church profile in Accounts. Your tagline and secondary
colour are still set in Events.
- **Tickets, invoices and certificates show your church's logo from Accounts** (PNG, JPEG or
SVG).
## 3.8.0
- **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number
gets no more WhatsApp messages from Cross Events, event updates and tickets included (they come
by email instead), and none from your church's other sites either. Before, STOP only stopped news
and announcements. They can turn WhatsApp back on from their account page in your church's
sign-in (or, if your church doesn't use it, by replying START).
- **Demo churches** for Cross Code's demo sites: eight demo churches, each with its own people,
staff and campuses, the same as on the demo Church Website and App. Never used on a real
church's site.
## 3.7.2
- **Fixed: events from your Church Website could show twice** after the website's content was
replaced. Cross Events now checks the full list every 15 minutes and removes events that are gone.
## 3.7.1
- **Connecting to your new Church Website works straight away**, so its events page can show your
+26 -2
View File
@@ -11,7 +11,27 @@ showing it to:
| `npm run demo:ministry` | One campus with weekly ministry | The Alpha Course running now (sessions, attendance, late joining, certificates), a finished Marriage Course with certificates, a 3-day conference sold by day, **Kids Church** with families, children, rooms and check-ins, **volunteer rosters**, a **Men's Breakfast series** with followers and a **season pass**, plus a family day, women's conference and carols. |
| `npm run demo:multicampus` | A church with several campuses | **Campuses** Central, North and South (switched on), events per campus and church-wide, home campuses, staff limited to a campus (Anri Botha → North, Daniel Pillay → South), the breakfast series moving between campuses, kids church and rosters at two campuses, and all the events-demo events spread over the campuses. |
`npm run demo:list` prints the same list. Kids church always has a session **today** with
**3.8.0: the eight demo scenarios** (docs/APP-1.0-PLAN.md §12). Each is named after its
Website demo profile and is one of the churches every product of a demo client shows:
| Profile | Church | Built as |
|---|---|---|
| `heritage-parish` | St Columba's Church | small |
| `heritage-city` | Grace Cathedral | events |
| `bold-youth` | Ignite Church | events |
| `bold-plant` | Harbour City Church | small |
| `community-family` | Acacia Hill Church (cross-demo2) | ministry |
| `community-town` | Karoo Gemeenskapskerk | small |
| `clean-modern` | Northpoint Church | ministry |
| `clean-campus` | Riverside Church (three campuses) | multicampus |
They use the church's own people from `@crosscode/demo` (its leads are the staff and the event
contacts; the same people, with the same accounts, as in Accounts, the Website and the App) and
its own campuses. Load Accounts' part first (`crosscode demo <church> accounts --profile …`), then
`npm run set-demo -- --profile=<scenario> --yes` (or `crosscode demo <church> --profile <scenario>`).
A small church's events sell only to the people it has.
`npm run demo:list` prints every profile. Kids church always has a session **today** with
children checked in right now, so the kids desk and room screens have something live to
show on any day.
@@ -63,9 +83,13 @@ previous demo and creates it again.
| The admin account, including its login history, trusted devices and 2FA | Every other user |
| Migration history | Registrations, payments, tickets, scans, coupons, waitlists, consents, cabins, feedback, analytics, audit log |
| Uploaded files on disk (`public/uploads`) | Queued scheduled emails/WhatsApps (`data/scheduled-emails.json`) |
| Links to the church's other products (Accounts, the Website) | Copies of the linked products' events (fetched again straight away) |
| The event feed's history: the old events are listed as removed | |
The wipe and the new data are written in one database transaction. If that fails,
nothing changes. The past events' cashups run straight afterwards, through the same
nothing changes. Since 3.7.2 the script then publishes the new events in the event feed and
tells the linked products (the Church Website), so their next page load shows the new events
and not the old ones, and fetches the linked products' events back in. The past events' cashups run straight afterwards, through the same
code as the cashup screen. If one of those fails, re-run the script.
---
+1 -1
View File
@@ -145,7 +145,7 @@ npm run prisma:generate
### Demo data
`npm run set-demo -- --profile=<small|events|ministry|multicampus>` wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
`npm run set-demo -- --profile=<small|events|ministry|multicampus|a demo scenario>` (3.8.0: the eight scenarios, e.g. `community-family`) wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
---
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.7.1",
"version": "3.9.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
@@ -25,6 +25,7 @@
"@cj-tech-master/excelts": "^10.2.0",
"@crosscode/auth-client": "*",
"@crosscode/contracts": "*",
"@crosscode/demo": "*",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
@@ -44,6 +45,7 @@
"pg-boss": "^11.1.2",
"qrcode": "^1.5.4",
"raw-body": "^3.0.0",
"svg-to-pdfkit": "0.1.8",
"swagger-ui-dist": "^5.34.0",
"tsx": "^4.23.15",
"typescript": "^5.9.3",
@@ -0,0 +1,14 @@
-- Cross Events 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): STOP to the church's WhatsApp number
-- means no WhatsApp from any of its products. Kept per account (from Accounts) and per number.
-- AlterTable
ALTER TABLE "User" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "WhatsAppStop" (
"phone" TEXT NOT NULL,
"keyword" TEXT NOT NULL,
"source" TEXT NOT NULL,
"receivedAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WhatsAppStop_pkey" PRIMARY KEY ("phone")
);
+14
View File
@@ -95,6 +95,10 @@ model User {
newsWhatsApp Boolean @default(false)
// When the person last answered the news opt-in question. Null = ask at next login.
newsAskedAt DateTime?
// 3.8.0: replied STOP to the church's WhatsApp number (here or to another of the church's
// products; Accounts keeps it and sends it in user.updated): no WhatsApp of any kind, until
// they turn it back on in Accounts. See also WhatsAppStop (by number).
whatsappOptedOut Boolean @default(false)
// The privacy notice version they last accepted (0 = the built-in notice). Null = never
// recorded. Asked again when a version that needs re-acceptance is newer.
noticeVersionAccepted Int?
@@ -1893,6 +1897,16 @@ model CommunicationConsent {
// Addresses (email, or phone as 27…) that unsubscribed from news without an account,
// e.g. ad-hoc broadcast recipients. News broadcasts skip them.
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): numbers that replied STOP to the church's WhatsApp
// number. Nothing goes to them on WhatsApp (src/utils/whatsappStop.js), with or without an account.
model WhatsAppStop {
phone String @id // 27821234567
keyword String
source String // events (this site's webhook) | accounts
receivedAt DateTime
createdAt DateTime @default(now())
}
model MessagingOptOut {
id String @id @default(uuid())
channel String // email | whatsapp
+141 -23
View File
@@ -16,6 +16,13 @@
* campus-limited staff, a series across campuses, kids check-in and rosters at two
* campuses.
*
* 3.8.0: and one per demo scenario (docs/APP-1.0-PLAN.md §12; contracts agent.DEMO_SCENARIOS),
* named after it (heritage-parish … clean-campus). A scenario's demo is built from one of the four
* kinds above, but around the scenario's own church: its people from @crosscode/demo (the same
* people, with the same church accounts, as in Accounts, the Website and the App; leads become the
* staff), and its own campuses. Load Accounts first (crosscode demo <church> accounts …), which
* makes those people's accounts; the demo then links to them rather than removing them.
*
* Everything is removed first EXCEPT the site settings (AppSetting) and one admin
* account (--admin-email= or DEMO_ADMIN_EMAIL; else joshua@crosscode.co.za, else the oldest admin).
* Dates are relative to
@@ -58,6 +65,8 @@ const { hashPassword } = require('../src/config/auth');
const { v4: uuidv4 } = require('uuid');
const { createPrismaClient } = require('../src/config/db');
const { applyBundles } = require('../src/utils/bundles');
const { agent } = require('@crosscode/contracts');
const demo = require('@crosscode/demo');
const prisma = createPrismaClient();
@@ -79,6 +88,9 @@ const KEEP_TABLES = new Set([
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
// its link nobody can sign in). Their feeds are data and go.
'ProductLink', 'LinkNonce',
// 3.7.2: what the feed last published. Its live entries are marked removed instead (clearData),
// so linked products are told the old events are gone, not left showing them beside the new.
'FeedEntry',
]);
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
@@ -233,7 +245,34 @@ function addUser({ first, last, gender, role = 'user', email }) {
return user;
}
/** The name of the nth demo staff member (the contact on events), for every profile. */
const staffName = (n) => (staffTeam[n] || staffTeam[0]).name;
/** The Events roles the scenario's leads get, in this order: the first four are the demo staff. */
const STAFF_PARTS = ['pastor', 'office', 'youth', 'worship', 'kids', 'prayer-coordinator'];
/** People in a scenario's Events demo besides its leads: not every member uses Events. */
const SCENARIO_MEMBERS = 260;
/** 3.8.0: a scenario's people (@crosscode/demo), as Accounts has them. */
function buildScenarioPeople(scenario) {
const all = demo.demoPeople(scenario);
const leads = all.filter(x => x.part !== 'member');
const staff = STAFF_PARTS.map(part => leads.find(x => x.part === part)).filter(Boolean).slice(0, 4);
const asUser = (person, role) => {
const user = addUser({ first: person.givenName, last: person.familyName, gender: person.gender, role, email: person.email });
userMeta.get(user.id).campus = person.campus;
return user;
};
staff.forEach((person, n) => staffTeam.push(asUser(person, n === 0 ? 'supervisor' : 'staff')));
const others = leads.filter(x => !staff.includes(x)).concat(all.filter(x => x.part === 'member').slice(0, SCENARIO_MEMBERS));
const users = others.map(person => asUser(person, 'user'));
const women = users.filter(u => userMeta.get(u.id).gender === 'female');
const men = users.filter(u => userMeta.get(u.id).gender === 'male');
return { women, men, everyone: women.concat(men) };
}
function buildPeople() {
if (profile.scenario) return buildScenarioPeople(profile.scenario);
staffTeam.push(
addUser({ first: 'Lerato', last: 'Khumalo', gender: 'female', role: 'supervisor', email: 'lerato.khumalo@example.com' }),
addUser({ first: 'Sipho', last: 'Dlamini', gender: 'male', role: 'staff', email: 'sipho.dlamini@example.com' }),
@@ -256,7 +295,7 @@ function addEvent(data) {
goLiveAt: addTime(NOW, -35 * DAY),
createdAt: addTime(NOW, -38 * DAY),
isActive: true,
contactName: 'Lerato Khumalo',
contactName: staffName(0),
contactEmail: 'events@example.com',
contactPhone: '021 555 0142',
...data,
@@ -536,7 +575,7 @@ function buildMensBreakfast(people) {
picture: IMG('photo-1414235077428-338989a2e8c0'),
location: 'Church hall',
waitlistEnabled: true,
contactName: 'Sipho Dlamini',
contactName: staffName(1),
});
const ticket = addOption(event, { name: 'Breakfast ticket', price: 150, stockLimit: 60 });
addSection(event, 'Hall entrance', [ticket]);
@@ -545,16 +584,17 @@ function buildMensBreakfast(people) {
const men = shuffle(people.men);
let sold = 0;
while (sold < 60) {
// 3.8.0: a small scenario church has fewer men than seats: sold to all of them, the rest left open.
while (sold < 60 && men.length > 7) {
const user = men.shift();
const quantity = Math.min(chance(0.2) ? 2 : 1, 60 - sold);
sold += quantity;
addRegistration(event, user, [line(ticket, quantity)], { createdAt: pastDate(28), ...payPlan({ card: 0.65, cash: 0.15, eft: 0.08, none: 0.12 }) });
}
for (let i = 0; i < 2; i++) {
for (let i = 0; i < 2 && men.length; i++) {
addRegistration(event, men.shift(), [line(ticket, 1)], { createdAt: pastDate(25, 5), pay: 'cancelled' });
}
for (let position = 1; position <= 5; position++) {
for (let position = 1; position <= 5 && sold >= 60 && men.length; position++) {
add('waitlistEntry', {
id: uuidv4(), eventId: event.id, eventOptionId: ticket.id, userId: men.shift().id,
quantity: position === 3 ? 2 : 1, position, status: 'waiting', createdAt: pastDate(4),
@@ -577,7 +617,7 @@ function buildWomensConference(people) {
price: 450,
picture: IMG('photo-1511632765486-a01980e01a18'),
location: 'Main auditorium',
contactName: 'Anri Botha',
contactName: staffName(2),
});
const full = addOption(event, { name: 'Full conference (Fri + Sat)', price: 450 });
const saturday = addOption(event, { name: 'Saturday only', price: 280 });
@@ -656,7 +696,7 @@ function buildYouthCamp(people) {
collectGender: true,
allowSponsorships: true,
sponsorshipGoalSpots: 10,
contactName: 'Daniel Pillay',
contactName: staffName(3),
});
const camper = addOption(event, { name: 'Camper (Grade 7–12)', price: 1650, stockLimit: 80 });
const hoodie = addOption(event, { name: 'Camp hoodie', price: 380, isMainTicket: false });
@@ -795,7 +835,7 @@ function buildMarriageWeekend(people) {
price: 3400,
picture: IMG('photo-1606800052052-a08af7148866'),
location: 'Kloofzicht Lodge, Muldersdrift',
contactName: 'Lerato Khumalo',
contactName: staffName(0),
});
const couple = addOption(event, { name: 'Couple package (2 nights)', price: 3400 });
const [garden, mountain] = addVariants(couple, [
@@ -884,22 +924,26 @@ function buildPastEvent(people, spec) {
for (const [label, type, amount, option] of spec.costs(opts)) addCost(event, label, type, amount, option || null);
const buyers = shuffle(people[spec.pool || 'everyone']);
const nextBuyer = () => {
if (buyers.length === 0) throw new Error(`Not enough demo people for ${spec.title}`);
return buyers.shift();
};
// 3.8.0: a small scenario church runs out of people before the event fills: the sales stop there.
const nextBuyer = () => buyers.shift() || null;
const salesFrom = addTime(start, -35 * DAY);
const payBy = addTime(start, -HOUR);
for (let i = 0; i < spec.online; i++) {
const plan = typeof spec.onlinePay === 'function' ? spec.onlinePay() : payPlan(spec.onlinePay);
addRegistration(event, nextBuyer(), spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -DAY)), payBy, ...plan });
const buyer = nextBuyer();
if (!buyer) break;
addRegistration(event, buyer, spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -DAY)), payBy, ...plan });
}
for (let i = 0; i < (spec.refunds || 0); i++) {
addRegistration(event, nextBuyer(), spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -10 * DAY)), pay: 'refunded', method: 'card' });
const buyer = nextBuyer();
if (!buyer) break;
addRegistration(event, buyer, spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -10 * DAY)), pay: 'refunded', method: 'card' });
}
for (let i = 0; i < (spec.door || 0); i++) {
const method = weighted(spec.doorPay || { cash: 70, card: 30 });
addRegistration(event, nextBuyer(), spec.lines(opts, true), { createdAt: within(addTime(start, -30 * MINUTE), addTime(start, HOUR)), method, atDoor: true });
const buyer = nextBuyer();
if (!buyer) break;
addRegistration(event, buyer, spec.lines(opts, true), { createdAt: within(addTime(start, -30 * MINUTE), addTime(start, HOUR)), method, atDoor: true });
}
const { card = 0, cash = 0, amounts = [] } = spec.donations || {};
@@ -1304,6 +1348,23 @@ const PROFILES = {
},
};
/** 3.8.0: the kind of demo each scenario is built from (APP-1.0-PLAN §12, the "Events" column). */
const SCENARIO_KINDS = {
'heritage-parish': 'small', 'heritage-city': 'events', 'bold-youth': 'events', 'bold-plant': 'small',
'community-family': 'ministry', 'community-town': 'small', 'clean-modern': 'ministry', 'clean-campus': 'multicampus',
};
for (const scenario of agent.DEMO_SCENARIOS) {
const kind = PROFILES[SCENARIO_KINDS[scenario.key]];
const church = demo.demoChurch(scenario.key);
PROFILES[scenario.key] = {
...kind,
scenario: scenario.key,
title: `${church.profile.name} — demo scenario (${scenario.label.split(':')[0]})`,
about: [scenario.description, `Built as the "${SCENARIO_KINDS[scenario.key]}" demo, with ${church.profile.name}'s own people${kind.campuses ? ' and campuses' : ''}. Load Accounts' part first.`],
campuses: church.profile.campuses.length > 0,
};
}
let profile = PROFILES[PROFILE_NAME];
const hex = (bytes = 16) => crypto.randomBytes(bytes).toString('hex');
@@ -1313,9 +1374,23 @@ let campuses = [];
function buildCampuses() {
const campus = (name, slug, address, colour, defaultLocation, order) => add('campus', {
id: uuidv4(), name, slug, address, contactName: 'Lerato Khumalo', contactEmail: `${slug}@example.com`,
id: uuidv4(), name, slug, address, contactName: staffName(0), contactEmail: `campus.${slug}@example.com`,
colour, defaultLocation, order, createdAt: addTime(NOW, -300 * DAY), updatedAt: NOW,
});
if (profile.scenario) {
// 3.8.0: the scenario church's own campuses, and people at the campus Accounts gives them.
const colours = ['#2563eb', '#16a34a', '#ea580c'];
campuses = demo.demoChurch(profile.scenario).profile.campuses.map((c, n) => campus(
c.name, c.slug, c.address ? [c.address.line1, c.address.suburb, c.address.city].filter(Boolean).join(', ') : null,
colours[n % colours.length], n === 0 ? 'Main auditorium' : `${c.name} campus hall`, n,
));
for (const u of rows.user) {
const slug = userMeta.get(u.id)?.campus;
const home = campuses.find(c => c.slug === slug);
if (u.role === 'user' && home) u.homeCampusId = home.id;
}
return;
}
campuses = [
campus('Central', 'central', '12 Church Street, Hatfield, Pretoria', '#2563eb', 'Main auditorium', 0),
campus('North', 'north', '45 Zambezi Drive, Montana', '#16a34a', 'North campus hall', 1),
@@ -1342,9 +1417,10 @@ function assignCampuses() {
/** Staff limited to one campus (a many-to-many, so it's set after the rows are in). */
async function scopeStaff(tx) {
const byName = (first) => staffTeam.find(s => s.name.startsWith(first));
for (const [first, campusIdx] of [['Anri', 1], ['Daniel', 2]]) {
await tx.user.update({ where: { id: byName(first).id }, data: { scopedCampuses: { connect: [{ id: campuses[campusIdx].id }] } } });
// The third and fourth demo staff (Anri Botha and Daniel Pillay in the multicampus demo).
for (const [staffIdx, campusIdx] of [[2, 1], [3, 2]]) {
if (!staffTeam[staffIdx] || !campuses[campusIdx]) continue;
await tx.user.update({ where: { id: staffTeam[staffIdx].id }, data: { scopedCampuses: { connect: [{ id: campuses[campusIdx].id }] } } });
}
}
@@ -1360,7 +1436,7 @@ function buildBreakfast(people, { start, title, sold }) {
price: 150,
picture: IMG('photo-1414235077428-338989a2e8c0'),
location: 'Church hall',
contactName: 'Sipho Dlamini',
contactName: staffName(1),
});
const ticket = addOption(event, { name: 'Breakfast ticket', price: 150, stockLimit: 60 });
addCost(event, 'Breakfast catering', 'per_item', 85, ticket);
@@ -1744,8 +1820,8 @@ function buildExtras(people, built) {
function listProfiles() {
console.log('\nDemo profiles — npm run demo:<name> (from the repo root):\n');
for (const [name, p] of Object.entries(PROFILES)) {
console.log(` ${name.padEnd(12)} ${p.title}`);
for (const line of p.about) console.log(` ${''.padEnd(12)} ${line}`);
console.log(` ${name.padEnd(17)} ${p.title}`);
for (const line of p.about) console.log(` ${''.padEnd(17)} ${line}`);
console.log('');
}
}
@@ -1823,6 +1899,10 @@ async function clearData(tx) {
await tx.$executeRawUnsafe(`UPDATE "User" SET ${[...new Set(userRefs.map(r => `"${r.column}" = NULL`))].join(', ')}`);
for (const table of deleteInstead) await tx.$executeRawUnsafe(`DELETE FROM "${table}"`);
}
// 3.7.2: every event the feed published goes into its `deleted` list, and the copies of linked
// products' events (truncated above) are fetched again in full.
await tx.feedEntry.updateMany({ where: { removedAt: null }, data: { removedAt: new Date() } });
await tx.productLink.updateMany({ data: { lastGoodAt: null } });
// Their password resets, 2FA codes and trusted devices go with them (onDelete: Cascade).
const { count } = await tx.user.deleteMany({ where: { id: { not: admin.id } } });
await tx.securityEvent.deleteMany({ where: { OR: [{ userId: null }, { userId: { not: admin.id } }] } });
@@ -1883,6 +1963,7 @@ async function main() {
}
passwordHash = await hashPassword(DEMO_PASSWORD);
const scenarioSubs = new Set(profile.scenario ? demo.demoPeople(profile.scenario).map(x => x.id) : []);
const people = buildPeople();
if (profile.campuses) buildCampuses();
const events = profile.upcoming.map(key => UPCOMING[key](people));
@@ -1893,7 +1974,9 @@ async function main() {
// 3.3.0: the church accounts of the people about to be cleared, so the old demo people leave
// Accounts too (only demo addresses; Accounts checks).
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId);
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId)
// 3.8.0: a scenario's people belong to Accounts' part of the scenario (loaded first): linked again, never removed.
.filter(sub => !scenarioSubs.has(sub));
const cleared = await prisma.$transaction(async (tx) => {
const result = await clearData(tx);
for (const model of INSERT_ORDER) {
@@ -1911,6 +1994,7 @@ async function main() {
clearScheduledEmails();
const pastFinancials = await closePastEvents();
const accounts = await demoAccounts(oldSubs);
const feed = await demoFeed();
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
@@ -1963,6 +2047,40 @@ async function main() {
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
}
if (feed && feed.links) console.log(`Connected products: ${feed.told} of ${feed.links} told the events changed${feed.failed ? `; ${feed.failed} couldn't be fetched from (the next poll catches up)` : ''}.`);
}
/**
* The backend's own code: the compiled code (dist/) on a server, the TypeScript through tsx in
* development. With dist/, its database client is a second one, disconnected at the end.
*/
function backendModule(rel) {
const dist = path.join(__dirname, '..', 'dist', `${rel}.js`);
if (fs.existsSync(dist)) {
accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db'));
return require(dist);
}
require('tsx/cjs');
return require(`../src/${rel}.ts`);
}
/**
* 3.7.2: the new events published in the feed straight away, linked products (the Website) told,
* so their next page load shows the new events without the old (marked removed in clearData), and
* their events fetched back in. Never fails the demo: the jobs catch up within 15 minutes.
*/
async function demoFeed() {
try {
const { refreshAndNotify } = backendModule('feed/notify');
const { syncAll } = backendModule('feed/sync');
const { told } = await refreshAndNotify(new Date());
const synced = await syncAll(new Date());
const links = await prisma.productLink.count();
return { links, told, failed: synced.failed };
} catch (e) {
console.warn(`[warn] The feed couldn't be refreshed now (${e.message}); the backend's feed jobs catch up within 15 minutes.`);
return null;
}
}
/**
+55 -6
View File
@@ -1,8 +1,11 @@
/**
* 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`).
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9). 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`: the brand style and the shared footer).
*
* The church's own details in it (name, logo, icon, colours, contact details) also win over
* this site's settings of the same name (`churchSettings`, through utils/settingsCache), so a change
* in Accounts (or a new demo church) shows here as it does on the church's Website.
*
* 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
@@ -12,6 +15,11 @@
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
import { accountsLink } from './client';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { setAccountsOverrides } = require('../utils/settingsCache') as { setAccountsOverrides(map: Record<string, string>): void };
const { pdfLogoPath } = require('../utils/logoCopy') as { pdfLogoPath(url: string): Promise<string | null> };
/* eslint-enable @typescript-eslint/no-require-imports */
const FRESH_MS = 10 * 60e3;
const RETRY_MS = 60e3;
const TIMEOUT_MS = 5000;
@@ -20,6 +28,28 @@ type Cached = { url: string; church: Church | null; at: number; ok: boolean };
let cached: Cached | null = null;
let pending: Promise<Church | null> | null = null;
/**
* This site's settings that the church profile sets, with its values. Only what the profile has:
* a church without an icon keeps this site's favicon, without an accent its accent colour.
* `secondary_color` and `org_tagline` aren't in the profile, so they stay this site's own.
*/
export function churchSettings(church: Church | null): Record<string, string> {
if (!church) return {};
const a = church.contact.address;
const address = a ? [a.line1, a.line2, a.suburb, a.city, a.province, a.postalCode].filter((x) => x && x.trim()).join(', ') : null;
const out: Record<string, string | null> = {
org_name: church.name,
logo_url: church.branding.logoUrl,
favicon_url: church.branding.iconUrl,
primary_color: church.branding.colours.primary,
accent_color: church.branding.colours.accent,
org_email: church.contact.email,
org_phone: church.contact.phone,
org_address: address,
};
return Object.fromEntries(Object.entries(out).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1] !== ''));
}
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}`);
@@ -36,7 +66,12 @@ export async function churchProfile(): Promise<Church | null> {
} catch {
return cached?.church ?? null;
}
if (!link) return null;
if (!link) {
// Disconnected from Accounts: this site's own settings again.
if (cached) cached = null;
setAccountsOverrides({});
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) {
@@ -44,10 +79,14 @@ export async function churchProfile(): Promise<Church | null> {
pending = fetchProfile(url)
.then((church) => {
cached = { url, church, at: Date.now(), ok: true };
setAccountsOverrides(churchSettings(church));
// A copy of the logo for PDFs, made now rather than while a ticket is being sent.
if (church.branding.logoUrl) pdfLogoPath(church.branding.logoUrl).catch(() => {});
return church;
}, (e: Error) => {
console.warn('[church] profile not fetched from Accounts:', e.message);
cached = { url, church: last, at: Date.now(), ok: false };
setAccountsOverrides(churchSettings(last));
return last;
})
.finally(() => { pending = null; });
@@ -55,13 +94,23 @@ export async function churchProfile(): Promise<Church | null> {
return pending;
}
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */
/** This site's settings the church profile sets right now (fetching it when it's due). Never throws. */
export async function churchSettingsNow(): Promise<Record<string, string>> {
return churchSettings(await churchProfile());
}
/**
* `church.changed`: fetched again straight away, so emails and pages that read the settings
* without waiting get the new details within moments (the last copy is used meanwhile).
*/
export function churchChanged(): void {
if (cached) cached = { ...cached, at: 0 };
churchProfile().catch(() => {});
}
/** Tests: start with nothing. */
export function resetChurchProfile(): void {
cached = null;
pending = null;
setAccountsOverrides({});
}
+2 -1
View File
@@ -7,7 +7,8 @@ import type { ChurchLook } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
// This site's own values: they fill what Accounts doesn't have, so never Accounts' own (settingsCache).
const { getStoredSetting: getSetting } = require('../utils/settingsCache') as { getStoredSetting(k: string, f?: string): Promise<string> };
/* eslint-enable @typescript-eslint/no-require-imports */
const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null);
+10 -1
View File
@@ -29,6 +29,7 @@ const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: stri
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
const whatsappStop = require('../utils/whatsappStop') as { clearStop(phone: string): Promise<string | null> };
/* eslint-enable @typescript-eslint/no-require-imports */
const PENDING_COOKIE = 'ev_signin';
@@ -107,7 +108,7 @@ export async function userForClaims(claims: IdentityClaims): Promise<{ user: Eve
}
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor']; whatsapp_opted_out?: boolean }) {
const data: Record<string, unknown> = {
name: profile.name,
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
@@ -125,7 +126,15 @@ export async function updateLocalCopy(userId: string, profile: Pick<IdentityClai
} else {
data.phoneNumber = null;
}
// 3.8.0: the WhatsApp opt-out Accounts keeps for every product (absent from an Accounts before 1.9.0).
if (profile.whatsapp_opted_out !== undefined) data.whatsappOptedOut = profile.whatsapp_opted_out;
const before = profile.whatsapp_opted_out === false ? await prisma.user.findUnique({ where: { id: userId }, select: { whatsappOptedOut: true, phoneNumber: true } }) : null;
await prisma.user.update({ where: { id: userId }, data });
// Turned back on in Accounts: this site's own STOP for the number goes too.
if (before?.whatsappOptedOut) {
const phone = (data.phoneNumber as string | null | undefined) ?? before.phoneNumber;
if (phone) await whatsappStop.clearStop(phone);
}
}
async function startSignIn(req: Request, res: Response) {
@@ -0,0 +1,34 @@
/**
* 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): a STOP this site's WhatsApp webhook received is
* passed on to the church's Accounts (`whatsapp.optout`, contracts 1.20.0), which keeps the opt-out
* for every product (the App, the Website, Accounts' own codes) and tells them all. Never fails the
* STOP itself: it's kept here either way.
*/
import { accounts, accountsLink } from './client';
import { viaAccounts } from './mode';
/** Passes a STOP on to Accounts; returns whether it did. `phone`: 27821234567. */
export async function stopInAccounts(phone: string, keyword: string): Promise<boolean> {
try {
if (!(await viaAccounts())) return false;
await (await accounts()).request({
type: 'whatsapp.optout', actor: null, phone: `+${phone.replace(/^\+/, '')}`,
receivedAt: new Date().toISOString(), keyword: String(keyword || 'STOP').trim().toUpperCase().slice(0, 40) || 'STOP',
});
return true;
} catch (e) {
console.warn('[accounts] WhatsApp STOP not passed on:', (e as Error).message);
return false;
}
}
/** Where someone turns WhatsApp back on: their account page in the church's Accounts. */
export async function accountPageUrl(): Promise<string | null> {
try {
if (!(await viaAccounts())) return null;
const link = await accountsLink();
return link ? `${link.url.replace(/\/$/, '')}/account` : null;
} catch {
return null;
}
}
@@ -41,11 +41,22 @@ const PUBLIC_KEYS = [
// @desc Get public app settings
// @route GET /api/settings
// @access Public
// The church's own details from its Accounts profile (name, logo, colours, contact): they win over
// this site's settings of the same name while Accounts is connected (src/accounts/church.ts).
async function fromAccounts() {
try {
return await require('../accounts/church').churchSettingsNow();
} catch {
return {};
}
}
const getSettings = async (req, res) => {
try {
const rows = await prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } });
const [rows, accounts] = await Promise.all([prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } }), fromAccounts()]);
const settings = {};
for (const r of rows) settings[r.key] = r.value;
for (const [k, v] of Object.entries(accounts)) if (PUBLIC_KEYS.includes(k)) settings[k] = v;
res.json(settings);
} catch (e) {
res.status(500).json({ message: safeErrorMessage(e) });
@@ -79,6 +90,11 @@ const getAllSettings = async (req, res) => {
settings[r.key] = r.value;
}
}
// What the site uses for the keys Accounts sets, and which they are, so Settings shows them
// read-only with a link to change them in Accounts.
const accounts = await fromAccounts();
Object.assign(settings, accounts);
settings.accounts_managed = Object.keys(accounts).join(',');
res.json(settings);
} catch (e) {
res.status(500).json({ message: safeErrorMessage(e) });
@@ -96,7 +112,7 @@ const updateSettings = async (req, res) => {
}
const ops = Object.entries(updates)
.filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k))
.filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k) && k !== 'accounts_managed')
.map(([key, value]) => {
let storedValue = String(value);
@@ -214,9 +214,11 @@ const handleWebhook = async (req, res) => {
/**
* An incoming WhatsApp message (WAWP `message` event). The only thing we act on is an
* opt-out reply — "STOP" — which stops News & announcements on WhatsApp for that number
* (event updates still go out). Only trusted when the URL carries our webhook secret,
* since WAWP doesn't sign webhooks.
* opt-out reply — "STOP". 3.8.0 (APP-1.0-PLAN decision 11): it stops all WhatsApp to that number
* from every one of the church's products, event updates and codes included: kept here
* (utils/whatsappStop), news turned off, and passed on to the church's Accounts, which tells the
* others. Turned back on in Accounts; a site without Accounts takes a "START" reply. Only trusted
* when the URL carries our webhook secret, since WAWP doesn't sign webhooks.
*/
async function handleIncomingMessage(req) {
const crypto = require('crypto');
@@ -236,16 +238,35 @@ async function handleIncomingMessage(req) {
prisma.appSetting.upsert({ where: { key: 'wawp_webhook_last_seen' }, update: { value: now }, create: { key: 'wawp_webhook_last_seen', value: now } }).catch(() => {});
const payload = req.body?.payload || {};
if (payload.fromMe || !isStopKeyword(payload.body)) return;
if (payload.fromMe) return;
const stop = isStopKeyword(payload.body);
const { isStartKeyword, recordStop, clearStop } = require('../utils/whatsappStop');
const { stopInAccounts, accountPageUrl } = require('../accounts/whatsappOptOut');
if (!stop && !isStartKeyword(payload.body)) return;
const phone = phoneFromChatId(payload.from);
if (!phone) {
// Groups, channels, and senders WhatsApp only identifies by a "LID" (no phone number).
console.warn('[whatsapp webhook] STOP from a sender without a phone number:', payload.from);
return;
}
const result = await whatsAppStop(phone);
if (!result) return;
await sendText(phone, "You won't get news and announcements from us on WhatsApp any more. You'll still get messages about events you've registered for.").catch(() => {});
const { getSettingSync } = require('../utils/settingsCache');
const church = getSettingSync('org_name', process.env.ORG_NAME || 'us');
const accountPage = await accountPageUrl();
if (!stop) {
// START: only without Accounts (with it, Accounts keeps the opt-out: turned back on there).
if (accountPage) {
await sendText(phone, `To get WhatsApp messages from ${church} again, turn them back on on your account page: ${accountPage}`, { evenIfStopped: true }).catch(() => {});
return;
}
await clearStop(phone);
await sendText(phone, `WhatsApp messages from ${church} are back on. Reply STOP at any time to stop them.`).catch(() => {});
return;
}
await recordStop(phone, { keyword: payload.body, source: 'events' });
await whatsAppStop(phone);
await stopInAccounts(phone, payload.body);
const undo = accountPage ? `To turn them back on, go to ${accountPage}` : 'Reply START to turn them back on.';
await sendText(phone, `You won't get WhatsApp messages from ${church} any more (event updates and codes come by email). ${undo}`, { evenIfStopped: true }).catch(() => {});
}
module.exports = {
+8 -3
View File
@@ -23,9 +23,14 @@ type Link = { installId: string; product: string; url: string; showEvents: boole
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; skipped?: number; error?: string };
export async function syncLink(link: Link, now = new Date()): Promise<SyncResult> {
/**
* `full` asks for the whole list and drops copies no longer in it: a sibling that loses events
* without listing them in `deleted` (a reseed, a restore) would otherwise leave stale copies
* beside the new ones for good.
*/
export async function syncLink(link: Link, now = new Date(), { full = false }: { full?: boolean } = {}): Promise<SyncResult> {
if (!link.showEvents) return { installId: link.installId, ok: true, imported: 0, deleted: 0 };
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
const since = !full && link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(link.url, FEED_PATHS.events, since ? { updatedSince: since.toISOString() } : {});
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
@@ -62,7 +67,7 @@ async function upsert(linkId: string, e: CrosscodeEvent) {
export async function syncAll(now = new Date()): Promise<{ links: number; failed: number }> {
const links: Link[] = await prisma.productLink.findMany({ where: { showEvents: true } });
let failed = 0;
for (const link of links) if (!(await syncLink(link, now)).ok) failed++;
for (const link of links) if (!(await syncLink(link, now, { full: true })).ok) failed++;
return { links: links.length, failed };
}
@@ -16,6 +16,7 @@ const fs = require('fs');
const path = require('path');
const PDFDocument = require('pdfkit');
const QRCode = require('qrcode');
const { drawLogo } = require('./logoCopy');
const prisma = require('../config/db');
const { activeSessions, completionMet, normalizeCertificateConfig, attendanceBySession, groupTickets, TIMEZONE } = require('./sessions');
@@ -189,7 +190,7 @@ function drawTemplate(doc, template, ctx) {
doc.rect(0, 0, 28, H).fill(color);
doc.rect(28, 0, 6, H).fill(lighten(color, 0.6));
const x = 90;
safeImage(doc, logo, x, 70, { fit: [120, 50] });
drawLogo(doc, logo, x, 70, { fit: [120, 50] });
doc.font('Helvetica').fontSize(11).fillColor(color).text(branding.name.toUpperCase(), x, 150, { characterSpacing: 2 });
doc.font('Helvetica-Bold').fontSize(36).fillColor('#0f172a').text(title, x, 175, { width: W - x - 80 });
doc.font('Helvetica').fontSize(13).fillColor('#64748b').text('Presented to', x, 260);
@@ -202,7 +203,7 @@ function drawTemplate(doc, template, ctx) {
if (template === 'church') {
doc.rect(0, 0, W, H).fill(lighten(color, 0.94));
doc.rect(30, 30, W - 60, H - 60).lineWidth(1).strokeColor(lighten(color, 0.4)).stroke();
const hasLogo = safeImage(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' });
const hasLogo = drawLogo(doc, logo, W / 2 - 50, 55, { fit: [100, 70], align: 'center' });
const top = hasLogo ? 150 : 115;
doc.font('Times-Italic').fontSize(14).fillColor(color).text(branding.name, 0, top, { width: W, align: 'center' });
doc.font('Times-Bold').fontSize(34).fillColor('#1e293b').text(title, 60, top + 26, { width: W - 120, align: 'center' });
@@ -228,7 +229,7 @@ function drawTemplate(doc, template, ctx) {
const y = top ? 48 + rnd() * 50 : 110 + rnd() * (H - 260);
doc.circle(x, y, 3 + rnd() * 5).fill(bright[i % bright.length]);
}
safeImage(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' });
drawLogo(doc, logo, W / 2 - 40, 100, { fit: [80, 50], align: 'center' });
doc.font('Helvetica-Bold').fontSize(38).fillColor(color).text(title, 100, 165, { width: W - 200, align: 'center' });
doc.font('Helvetica-Bold').fontSize(15).fillColor('#f59e0b').text('Well done,', 0, 230, { width: W, align: 'center' });
doc.font('Helvetica-Bold').fontSize(36).fillColor('#1e293b').text(cert.name, 100, 250, { width: W - 200, align: 'center' });
@@ -244,7 +245,7 @@ function drawTemplate(doc, template, ctx) {
for (const [cx, cy] of [[34, 34], [W - 34, 34], [34, H - 34], [W - 34, H - 34]]) {
doc.circle(cx, cy, 6).fill(color);
}
safeImage(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' });
drawLogo(doc, logo, W / 2 - 45, 70, { fit: [90, 55], align: 'center' });
doc.font('Times-Bold').fontSize(38).fillColor('#1e293b').text(title.toUpperCase(), 60, 150, { width: W - 120, align: 'center', characterSpacing: 1.5 });
doc.font('Times-Italic').fontSize(14).fillColor('#64748b').text('This certificate is proudly presented to', 0, 212, { width: W, align: 'center' });
doc.font('Times-BoldItalic').fontSize(34).fillColor(color).text(cert.name, 60, 236, { width: W - 120, align: 'center' });
+137
View File
@@ -0,0 +1,137 @@
// The logo for PDFs (tickets, invoices, receipts, certificates, privacy exports). PDFs need a file
// on disk. A logo uploaded here already is one; the church's logo from its Accounts profile is an
// address on another site, so a copy is kept in uploads/accounts (one per address, made when the
// profile arrives or the first PDF needs it; older copies are removed).
//
// PNG and JPEG are drawn as pictures; SVG (the demo churches' logos, and many churches') is drawn
// as shapes with svg-to-pdfkit (`drawLogo`). Anything else (WebP, GIF) isn't copied, and the PDFs
// show the church's name without a logo.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const SVGtoPDF = require('svg-to-pdfkit');
const { UPLOADS_DIR, uploadsDir } = require('./uploads');
const MAX_BYTES = 2 * 1024 * 1024;
const TIMEOUT_MS = 5000;
const EXT = { png: 'png', jpeg: 'jpg', svg: 'svg' };
/** PNG, JPEG or SVG by the file's own bytes (never by what a server says it is), else null. */
function logoKind(buf) {
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';
const head = buf.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart();
if (head.startsWith('<') && /<svg[\s>]/i.test(head)) return 'svg';
return null;
}
const nameFor = (url) => `logo-${crypto.createHash('sha256').update(url).digest('hex').slice(0, 16)}`;
/** An outside address the site may fetch the logo from: https, or http while developing. */
function fetchable(url) {
try {
const u = new URL(url);
return u.protocol === 'https:' || (u.protocol === 'http:' && process.env.NODE_ENV !== 'production');
} catch {
return false;
}
}
function existingCopy(url) {
const base = nameFor(url);
for (const ext of Object.values(EXT)) {
const p = path.join(UPLOADS_DIR, 'accounts', `${base}.${ext}`);
if (fs.existsSync(p)) return p;
}
return null;
}
// Addresses tried lately that gave no usable logo: not fetched again for 10 minutes.
const misses = new Map();
const MISS_MS = 10 * 60e3;
const pending = new Map();
async function download(url) {
const res = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'follow' });
if (!res.ok) throw new Error(`answered ${res.status}`);
if (Number(res.headers.get('content-length') || 0) > MAX_BYTES) throw new Error('is larger than 2 MB');
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length > MAX_BYTES) throw new Error('is larger than 2 MB');
const kind = logoKind(buf);
if (!kind) return null; // WebP, GIF…: not drawable in a PDF
const dir = uploadsDir('accounts');
const base = nameFor(url);
const file = path.join(dir, `${base}.${EXT[kind]}`);
fs.writeFileSync(file, buf);
// The church changed its logo: the copies of the old ones go.
for (const f of fs.readdirSync(dir)) if (f.startsWith('logo-') && !f.startsWith(`${base}.`)) fs.rmSync(path.join(dir, f), { force: true });
return file;
}
/**
* The logo as a file a PDF can draw (`drawLogo`), or null. `logoUrl` is the logo_url setting: a
* path on this site (/uploads/…) or the church's logo address from Accounts. Never throws.
*/
async function pdfLogoPath(logoUrl) {
const url = String(logoUrl || '').trim();
if (!url) return null;
if (!/^https?:\/\//i.test(url)) {
const p = path.join(UPLOADS_DIR, '..', url.replace(/^\//, ''));
try {
return fs.existsSync(p) && logoKind(fs.readFileSync(p)) ? p : null;
} catch {
return null;
}
}
if (!fetchable(url)) return null;
const have = existingCopy(url);
if (have) return have;
const missed = misses.get(url);
if (missed && Date.now() - missed < MISS_MS) return null;
if (!pending.has(url)) {
pending.set(url, download(url)
.catch((e) => {
console.warn(`[logo] the church's logo couldn't be copied for PDFs: ${url} ${e.message}`);
return null;
})
.then((file) => {
if (!file) misses.set(url, Date.now());
return file;
})
.finally(() => pending.delete(url)));
}
return pending.get(url);
}
/**
* Draws the logo `file` (from pdfLogoPath) at x, y within `fit` [w, h], as doc.image does; centred
* in that box with `align: 'center'`. True when drawn. Never throws.
*/
function drawLogo(doc, file, x, y, { fit, align } = {}) {
if (!file) return false;
try {
if (file.toLowerCase().endsWith('.svg')) {
const [width, height] = fit || [100, 50];
SVGtoPDF(doc, fs.readFileSync(file, 'utf8'), x, y, {
width,
height,
preserveAspectRatio: align === 'center' ? 'xMidYMid meet' : 'xMinYMid meet',
// Only pictures inside the SVG itself: never a file or address it names.
imageCallback: (link) => (/^data:image\/(png|jpe?g);base64,/i.test(String(link).trim()) ? String(link).replace(/\s+/g, '') : ''),
warningCallback: () => {},
});
} else {
doc.image(file, x, y, { fit, ...(align ? { align } : {}) });
}
return true;
} catch {
return false;
}
}
/** Tests: forget the addresses that gave nothing. */
function resetLogoCopies() {
misses.clear();
}
module.exports = { pdfLogoPath, drawLogo, resetLogoCopies, logoKind };
+4 -7
View File
@@ -55,11 +55,8 @@ async function getBranding() {
getSetting('logo_url', ''),
]);
const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
let logoPath = null;
if (logoUrl) {
const p = path.join(__dirname, '..', '..', 'public', logoUrl.replace(/^\//, ''));
if (fs.existsSync(p)) logoPath = p;
}
// An uploaded logo, or a copy of the church's logo from Accounts (utils/logoCopy.js).
const logoPath = await require('./logoCopy').pdfLogoPath(logoUrl);
return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath };
}
@@ -196,7 +193,7 @@ async function generateReceiptPdf(payment) {
const bannerH = 150;
doc.rect(0, 0, pageWidth, bannerH).fill(org.brandColor);
if (org.logoPath) {
try { doc.image(org.logoPath, marginX, 28, { fit: [36, 36] }); } catch {}
require('./logoCopy').drawLogo(doc, org.logoPath, marginX, 28, { fit: [36, 36] });
}
doc.fillColor('#ffffff').font('Helvetica-Bold').fontSize(13).text(org.name, marginX + (org.logoPath ? 46 : 0), 38, { width: 260 });
doc.font('Helvetica-Bold').fontSize(26).text('Payment Receipt', marginX, 68, { width: 320 });
@@ -301,7 +298,7 @@ async function generateInvoicePdf(registration, { paymentUrl = null, totalDue =
doc.rect(0, 0, sidebarW, pageHeight).fill('#111827');
let sy = 40;
if (org.logoPath) {
try { doc.image(org.logoPath, 28, sy, { fit: [32, 32] }); sy += 0; } catch {}
require('./logoCopy').drawLogo(doc, org.logoPath, 28, sy, { fit: [32, 32] });
}
doc.font('Helvetica-Bold').fontSize(12).fillColor('#ffffff').text(org.name, org.logoPath ? 68 : 28, sy + 8, { width: sidebarW - (org.logoPath ? 96 : 56) });
sy += 60;
+2 -1
View File
@@ -270,7 +270,8 @@ function whatsAppNewsFooter(recipient) {
/** Recognises an opt-out reply ("STOP", "stop.", "Unsubscribe"). */
function isStopKeyword(text) {
return /^\s*(stop|unsubscribe|stop all|opt out|optout)\s*[.!]?\s*$/i.test(String(text || ''));
// 3.8.0: STOPP and UITTEKEN (Afrikaans) too, as the church's Accounts reads them.
return /^\s*(stop|stopp|unsubscribe|stop all|opt out|optout|uitteken)\s*[.!]?\s*$/i.test(String(text || ''));
}
/**
+42 -1
View File
@@ -17,9 +17,37 @@ let _cache = {};
let _lastFetch = 0;
const TTL_MS = 60 * 1000;
/**
* The church's own details from its Accounts profile (src/accounts/church.ts): name, logo, icon,
* colours and contact details. Accounts owns them, so while it's connected they win over this
* site's own settings everywhere (pages, emails, PDFs). Empty without Accounts.
*/
let _fromAccounts = {};
/** Set by src/accounts/church.ts whenever it has (or loses) the church profile. */
function setAccountsOverrides(map) {
_fromAccounts = { ...(map || {}) };
}
/** The keys Accounts sets right now, with their values. */
function accountsOverrides() {
return { ..._fromAccounts };
}
/** The church profile is kept fresh as the settings are (it caches itself for 10 minutes). */
function refreshChurchProfile() {
try {
const p = require('../accounts/church').churchProfile();
if (p && typeof p.catch === 'function') p.catch(() => {});
} catch {
// No Accounts code in this context (some tests): the site's own settings stand.
}
}
async function refreshIfStale() {
const now = Date.now();
if (now - _lastFetch < TTL_MS && _lastFetch > 0) return;
refreshChurchProfile();
try {
const rows = await prisma.appSetting.findMany();
const fresh = {};
@@ -38,6 +66,13 @@ async function refreshIfStale() {
* @returns {string}
*/
function _getSync(key, envFallback = '') {
const a = _fromAccounts[key];
if (typeof a === 'string' && a !== '') return a;
return _getStoredSync(key, envFallback);
}
/** This site's own value, ignoring Accounts (for sending this site's look to Accounts, src/accounts/look.ts). */
function _getStoredSync(key, envFallback = '') {
const v = _cache[key];
const raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || '');
if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) {
@@ -76,4 +111,10 @@ function invalidate() {
refreshIfStale().catch(() => {});
}
module.exports = { getSetting, getSettingSync, warmCache, invalidate, ENCRYPTED_KEYS };
/** As getSetting, but this site's own value even when Accounts sets the key. */
async function getStoredSetting(key, envFallback = '') {
await refreshIfStale();
return _getStoredSync(key, envFallback);
}
module.exports = { getSetting, getSettingSync, getStoredSetting, warmCache, invalidate, setAccountsOverrides, accountsOverrides, ENCRYPTED_KEYS };
@@ -186,6 +186,8 @@ async function deliverCode(user, method, code, { allowFallback = true } = {}) {
try {
// sendText silently no-ops when WhatsApp isn't set up, so check first.
if (!isValidZAPhone(user.phoneNumber) || !(await isConfigured())) throw new Error('WhatsApp unavailable');
// 3.8.0: they replied STOP, so no WhatsApp: the code goes by email.
if (await require('./whatsappStop').isWhatsAppStopped(user.phoneNumber)) throw new Error('WhatsApp turned off (STOP)');
await sendText(user.phoneNumber, buildWATwoFactorCode({ name: user.name, code }));
return { method: 'whatsapp', destination: maskPhone(user.phoneNumber) };
} catch (e) {
+13 -1
View File
@@ -222,10 +222,18 @@ async function requestPairingCode(phoneNumber) {
// ─── Messaging ────────────────────────────────────────────────────────────────
async function sendText(toPhone, message) {
/**
* 3.8.0: nothing goes to a number that replied STOP (utils/whatsappStop.js), unless `evenIfStopped`
* (only the one reply that confirms the STOP). Returns false when it skipped.
*/
async function sendText(toPhone, message, { evenIfStopped = false } = {}) {
if (!(await isConfigured())) return;
const chatId = toChatId(toPhone);
if (!chatId) { console.warn('[whatsapp] Invalid phone, skipping text:', toPhone); return; }
if (!evenIfStopped && (await require('./whatsappStop').isWhatsAppStopped(toPhone))) {
console.info('[whatsapp] Not sent: the number replied STOP.');
return false;
}
const { token, instanceId } = await getConfig();
try {
await axios.post(`${BASE}/send/text`, {
@@ -251,6 +259,10 @@ async function sendPdf(toPhone, localPdfPath, filename, caption) {
if (!(await isConfigured())) return;
const chatId = toChatId(toPhone);
if (!chatId) { console.warn('[whatsapp] Invalid phone, skipping PDF:', toPhone); return; }
if (await require('./whatsappStop').isWhatsAppStopped(toPhone)) {
console.info('[whatsapp] PDF not sent: the number replied STOP.');
return false;
}
const tempDir = path.join(__dirname, '../../public/uploads/tickets-temp');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
@@ -0,0 +1,63 @@
/**
* 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): a STOP to the church's WhatsApp number means no
* WhatsApp from any of the church's products, event updates and codes included, until the person
* turns it back on (in the church's Accounts; or, without Accounts, by replying START here).
*
* Two records, either of which stops a message:
* - `WhatsAppStop`, by number: STOPs this site's webhook received (with or without an account).
* - `User.whatsappOptedOut`: from Accounts (`user.updated` carries `whatsapp_opted_out`), so a STOP
* another product received reaches Events too.
*
* `sendText` / `sendPdf` (utils/whatsapp.js) check `isWhatsAppStopped` before every message.
*/
'use strict';
const prisma = require('../config/db');
function normalise(raw) {
return require('./whatsapp').normalizeZAPhone(raw);
}
/** The ways a number may be stored on an account: 27821234567, +27821234567, 0821234567. */
function storedForms(n) {
return [n, `+${n}`, `0${n.slice(2)}`];
}
/** Whether nothing may go to this number on WhatsApp. */
async function isWhatsAppStopped(rawPhone) {
const n = normalise(rawPhone);
if (!n) return false;
if (await prisma.whatsAppStop.findUnique({ where: { phone: n } })) return true;
const user = await prisma.user.findFirst({ where: { whatsappOptedOut: true, phoneNumber: { in: storedForms(n) } }, select: { id: true } });
return !!user;
}
/** A STOP from this number: kept, and every account with it opted out. Returns the number (27…) or null. */
async function recordStop(rawPhone, { keyword, source = 'events' }) {
const n = normalise(rawPhone);
if (!n) return null;
const word = String(keyword || 'STOP').trim().toUpperCase().slice(0, 40);
await prisma.whatsAppStop.upsert({
where: { phone: n },
update: { keyword: word, source, receivedAt: new Date() },
create: { phone: n, keyword: word, source, receivedAt: new Date() },
});
await prisma.user.updateMany({ where: { phoneNumber: { in: storedForms(n) } }, data: { whatsappOptedOut: true } });
return n;
}
/** WhatsApp back on for this number (Accounts said so, or a START here without Accounts). */
async function clearStop(rawPhone) {
const n = normalise(rawPhone);
if (!n) return null;
await prisma.whatsAppStop.deleteMany({ where: { phone: n } });
await prisma.user.updateMany({ where: { phoneNumber: { in: storedForms(n) } }, data: { whatsappOptedOut: false } });
return n;
}
/** "START" (or "BEGIN", Afrikaans "BEGIN"/"AAN"): WhatsApp back on, for a site without Accounts. */
function isStartKeyword(text) {
return /^\s*(start|unstop|begin|aan)\s*[.!]?\s*$/i.test(String(text || ''));
}
module.exports = { isWhatsAppStopped, recordStop, clearStop, isStartKeyword, storedForms };
@@ -207,7 +207,7 @@ export const syncNow = defineRoute({
async handler({ params }) {
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
if (!link) throw notFound('That connected product');
await syncLink(link);
await syncLink(link, new Date(), { full: true });
return { data: await overview() };
},
});
@@ -0,0 +1,42 @@
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): the WhatsApp opt-out Accounts keeps for every
// product reaches Events in user.updated (`whatsapp_opted_out`), both ways.
const mockUpdates: { id: string; data: Record<string, unknown> }[] = [];
let mockBefore: { whatsappOptedOut: boolean; phoneNumber: string | null } | null = null;
jest.mock('../src/config/db', () => ({
user: {
findFirst: async () => null,
findUnique: async () => mockBefore,
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => { mockUpdates.push({ id: where.id, data }); return {}; },
},
}));
jest.mock('../src/utils/whatsappStop', () => ({ clearStop: jest.fn().mockResolvedValue('27821234567') }));
import { updateLocalCopy } from '../src/accounts/signin';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { clearStop } = require('../src/utils/whatsappStop') as { clearStop: jest.Mock };
const profile = (over: Record<string, unknown> = {}) => ({
name: 'Thandi Example', email: 'thandi@hope.test', phone_number: '+27821234567', news_consent: { email: true, whatsapp: false }, ...over,
});
beforeEach(() => { mockUpdates.length = 0; mockBefore = null; clearStop.mockClear(); });
test('opted out in Accounts: no WhatsApp here either', async () => {
await updateLocalCopy('u1', profile({ whatsapp_opted_out: true }));
expect(mockUpdates[0]!.data.whatsappOptedOut).toBe(true);
expect(clearStop).not.toHaveBeenCalled();
});
test('turned back on in Accounts: on here, and this site\'s own STOP for the number goes', async () => {
mockBefore = { whatsappOptedOut: true, phoneNumber: '+27821234567' };
await updateLocalCopy('u1', profile({ whatsapp_opted_out: false }));
expect(mockUpdates[0]!.data.whatsappOptedOut).toBe(false);
expect(clearStop).toHaveBeenCalledWith('+27821234567');
});
test('an Accounts before 1.9.0 (no field) changes nothing about it', async () => {
await updateLocalCopy('u1', profile());
expect('whatsappOptedOut' in mockUpdates[0]!.data).toBe(false);
});
@@ -37,8 +37,9 @@ const realFetch = global.fetch;
beforeAll(() => {
global.fetch = (async (url: string) => {
// The logo, copied for PDFs (utils/logoCopy.js): not part of these tests.
if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 });
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' } });
@@ -0,0 +1,128 @@
// The church's own details from Accounts (name, logo, icon, colours, contact) win over this site's
// settings of the same name: on the public settings, in Settings (read-only), and for everything
// that reads them through the settings cache (emails, PDFs). Without Accounts, the site's own stand.
import fs from 'fs';
import path from 'path';
type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date };
const mockLinks: Link[] = [];
const mockRows: { key: string; value: string }[] = [];
jest.mock('../src/config/db', () => ({
productLink: {
findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null,
},
appSetting: {
findMany: async (q?: { where?: { key?: { in?: string[] } } }) => mockRows.filter((r) => !q?.where?.key?.in || q.where.key.in.includes(r.key)),
},
}));
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
import { CHURCH_PATHS } from '@crosscode/contracts';
import { churchProfile, churchSettings, resetChurchProfile } from '../src/accounts/church';
import { churchLook } from '../src/accounts/look';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const settingsCache = require('../src/utils/settingsCache');
const { getSettings, getAllSettings } = require('../src/controllers/settingsController');
/* eslint-enable @typescript-eslint/no-require-imports */
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
const sample = () => JSON.parse(fs.readFileSync(path.join(SAMPLES, 'church.json'), 'utf8'));
let profile = sample();
const realFetch = global.fetch;
beforeAll(() => {
global.fetch = (async (url: string) => {
if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 }); // the logo (logoCopy tests)
return new Response(JSON.stringify(profile), { status: 200, headers: { 'content-type': 'application/json' } });
}) as typeof fetch;
});
afterAll(() => { global.fetch = realFetch; });
beforeEach(() => {
resetChurchProfile();
mockLinks.length = 0;
mockRows.length = 0;
mockRows.push(
{ key: 'org_name', value: 'Old Demo Church' },
{ key: 'org_tagline', value: 'Our own tagline' },
{ key: 'primary_color', value: '#111111' },
{ key: 'secondary_color', value: '#222222' },
{ key: 'logo_url', value: '/uploads/old-logo.png' },
);
settingsCache.invalidate();
profile = sample();
});
const connectAccounts = () => mockLinks.push({ installId: 'acc', product: 'accounts', url: 'https://accounts.hope.test/', secret: 'x', updatedAt: new Date() });
async function call(handler: (req: unknown, res: unknown) => Promise<void>): Promise<Record<string, string>> {
let body: Record<string, string> = {};
await handler({}, { json: (b: Record<string, string>) => { body = b; }, status() { return this; } });
return body;
}
describe("the church's details from Accounts", () => {
test('only what the profile has', () => {
profile.branding.iconUrl = null;
profile.branding.colours.accent = null;
const s = churchSettings(profile);
expect(s.org_name).toBe(profile.name);
expect(s.primary_color).toBe(profile.branding.colours.primary);
expect('favicon_url' in s).toBe(false);
expect('accent_color' in s).toBe(false);
expect(churchSettings(null)).toEqual({});
});
test('without Accounts, the site keeps its own', async () => {
const s = await call(getSettings);
expect(s.org_name).toBe('Old Demo Church');
expect((await call(getAllSettings)).accounts_managed).toBe('');
});
test("with Accounts, the public settings show the church's, and keep what the profile doesn't set", async () => {
connectAccounts();
const s = await call(getSettings);
expect(s.org_name).toBe(profile.name);
expect(s.primary_color).toBe(profile.branding.colours.primary);
expect(s.logo_url).toBe(profile.branding.logoUrl);
expect(s.org_tagline).toBe('Our own tagline');
expect(s.secondary_color).toBe('#222222');
});
test('Settings marks the ones Accounts sets', async () => {
connectAccounts();
const all = await call(getAllSettings);
expect(all.org_name).toBe(profile.name);
expect(all.accounts_managed.split(',')).toEqual(expect.arrayContaining(['org_name', 'primary_color', 'logo_url']));
expect(all.accounts_managed.split(',')).not.toContain('secondary_color');
});
test('the settings cache (emails, PDFs) uses them once the profile is in, and the look sent to Accounts stays the site\'s own', async () => {
connectAccounts();
await settingsCache.warmCache();
await churchProfile();
expect(settingsCache.getSettingSync('org_name', 'Cross Code')).toBe(profile.name);
expect(await settingsCache.getStoredSetting('org_name')).toBe('Old Demo Church');
expect((await churchLook()).name).toBe('Old Demo Church');
});
test('a church that changes its name in Accounts (a new demo church) is shown after church.changed', async () => {
connectAccounts();
await churchProfile();
profile.name = 'Grace Fellowship';
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('../src/accounts/church').churchChanged();
await churchProfile();
expect(settingsCache.getSettingSync('org_name')).toBe('Grace Fellowship');
expect((await call(getSettings)).org_name).toBe('Grace Fellowship');
});
test('disconnected from Accounts: back to the site\'s own', async () => {
connectAccounts();
await churchProfile();
mockLinks.length = 0;
await churchProfile();
expect(settingsCache.getSettingSync('org_name')).toBe('Old Demo Church');
});
});
@@ -399,6 +399,16 @@ describe('events from a linked product', () => {
expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince=');
});
test('a full fetch (the poll) drops copies of events the source lost without saying (a reseed)', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
db.t.importedEvent.set('website:old', { key: 'website:old', linkId: WEBSITE_ID });
const e = sample();
answer(feedOf([e]));
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW, { full: true });
expect(String(global.fetch.mock.calls[0][0])).not.toContain('updatedSince=');
expect([...db.t.importedEvent.keys()]).toEqual([`website:${e.id}`]);
});
test('deleted events go; never re-published in this site\'s own feed', async () => {
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
const e = sample();
+126
View File
@@ -0,0 +1,126 @@
// The logo for PDFs: an uploaded one is used as it is; the church's logo from Accounts (an address
// on another site) is copied into uploads/accounts once, when it's a PNG, JPEG or SVG; drawLogo
// draws either kind into a PDF.
import fs from 'fs';
import path from 'path';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { pdfLogoPath, drawLogo, resetLogoCopies } = require('../src/utils/logoCopy') as {
pdfLogoPath(u: string): Promise<string | null>;
drawLogo(doc: unknown, file: string | null, x: number, y: number, o?: { fit?: [number, number]; align?: string }): boolean;
resetLogoCopies(): void;
};
const PDFDocument = require('pdfkit');
const { UPLOADS_DIR } = require('../src/utils/uploads') as { UPLOADS_DIR: string };
/* eslint-enable @typescript-eslint/no-require-imports */
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]);
const SVG = Buffer.from('<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#1f4e79"/><path d="M232 96h48v320h-48z" fill="#fff"/></svg>');
const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 ')]);
const COPIES = path.join(UPLOADS_DIR, 'accounts');
const realFetch = global.fetch;
let served: Record<string, Buffer | number> = {};
let fetched: string[] = [];
beforeAll(() => {
global.fetch = (async (url: string) => {
fetched.push(url);
const body = served[url];
if (body === undefined || typeof body === 'number') return new Response('', { status: typeof body === 'number' ? body : 404 });
return new Response(new Uint8Array(body), { status: 200 });
}) as typeof fetch;
});
afterAll(() => {
global.fetch = realFetch;
fs.rmSync(COPIES, { recursive: true, force: true });
});
beforeEach(() => {
fs.rmSync(COPIES, { recursive: true, force: true });
resetLogoCopies();
served = {};
fetched = [];
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => { jest.restoreAllMocks(); });
function pdfOf(draw: (doc: unknown) => void): Promise<string> {
return new Promise((resolve) => {
const doc = new PDFDocument({ compress: false });
const parts: Buffer[] = [];
doc.on('data', (b: Buffer) => parts.push(b));
doc.on('end', () => resolve(Buffer.concat(parts).toString('latin1')));
draw(doc);
doc.end();
});
}
test("the church's PNG logo from Accounts is copied once, and used from the copy after", async () => {
served['https://accounts.hope.test/logo.png'] = PNG;
const p = await pdfLogoPath('https://accounts.hope.test/logo.png');
expect(p && path.dirname(p)).toBe(COPIES);
expect(fs.readFileSync(p!)).toEqual(PNG);
expect(await pdfLogoPath('https://accounts.hope.test/logo.png')).toBe(p);
expect(fetched).toHaveLength(1);
});
test('a new logo replaces the copy of the old one', async () => {
served['https://accounts.hope.test/old.png'] = PNG;
served['https://accounts.hope.test/new.png'] = PNG;
const old = await pdfLogoPath('https://accounts.hope.test/old.png');
const next = await pdfLogoPath('https://accounts.hope.test/new.png');
expect(next).not.toBe(old);
expect(fs.existsSync(old!)).toBe(false);
expect(fs.readdirSync(COPIES)).toHaveLength(1);
});
test("an SVG logo (the demo churches') is copied too", async () => {
served['https://accounts.hope.test/logo.svg'] = SVG;
const p = await pdfLogoPath('https://accounts.hope.test/logo.svg');
expect(p?.endsWith('.svg')).toBe(true);
});
test("a logo a PDF can't draw, or one that can't be fetched, gives none (the PDF shows the name), and isn't fetched again at once", async () => {
served['https://accounts.hope.test/logo.webp'] = WEBP;
served['https://accounts.hope.test/gone.png'] = 404;
expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull();
expect(await pdfLogoPath('https://accounts.hope.test/gone.png')).toBeNull();
expect(await pdfLogoPath('https://accounts.hope.test/logo.webp')).toBeNull();
expect(fetched).toHaveLength(2);
});
test('drawLogo draws an SVG logo as shapes in its colours, and never opens a file the SVG names', async () => {
fs.mkdirSync(COPIES, { recursive: true });
const file = path.join(COPIES, 'logo-test.svg');
fs.writeFileSync(file, SVG);
let drawn = false;
const pdf = await pdfOf((doc) => { drawn = drawLogo(doc, file, 40, 40, { fit: [60, 60], align: 'center' }); });
expect(drawn).toBe(true);
expect(pdf).toMatch(/0\.12156\d* 0\.30588\d* 0\.47450\d* scn/); // #1f4e79
const picture = path.join(COPIES, 'logo-test.png');
fs.writeFileSync(picture, PNG);
const sneaky = path.join(COPIES, 'logo-sneaky.svg');
const href = picture.split(path.sep).join('/');
fs.writeFileSync(sneaky, `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><image href="${href}" width="10" height="10"/></svg>`);
const out = await pdfOf((doc) => { drawLogo(doc, sneaky, 0, 0, { fit: [10, 10] }); });
expect(out).not.toContain('/Subtype /Image');
});
test("drawLogo gives false, without throwing, for a file it can't draw", async () => {
fs.mkdirSync(COPIES, { recursive: true });
const bad = path.join(COPIES, 'logo-bad.png');
fs.writeFileSync(bad, 'not a picture');
let drawn = true;
await pdfOf((doc) => { drawn = drawLogo(doc, bad, 0, 0, { fit: [10, 10] }); });
expect(drawn).toBe(false);
expect(drawLogo({}, null, 0, 0)).toBe(false);
});
test('a logo uploaded here is used as it is; nothing for no logo', async () => {
fs.mkdirSync(COPIES, { recursive: true });
fs.writeFileSync(path.join(COPIES, 'own.png'), PNG);
expect(await pdfLogoPath('/uploads/accounts/own.png')).toBe(path.join(COPIES, 'own.png'));
expect(await pdfLogoPath('')).toBeNull();
expect(await pdfLogoPath('/uploads/accounts/missing.png')).toBeNull();
expect(fetched).toHaveLength(0);
});
@@ -78,6 +78,7 @@ jest.mock('../src/utils/email', () => ({
buildTwoFactorCodeEmail: ({ code }) => ({ text: `code:${code}`, html: '' }),
}));
jest.mock('../src/utils/waMessages', () => ({ buildWATwoFactorCode: ({ code }) => `code:${code}` }));
jest.mock('../src/utils/whatsappStop', () => ({ isWhatsAppStopped: async () => false }));
jest.mock('../src/utils/whatsapp', () => ({
isValidZAPhone: (p) => /^27\d{9}$/.test(String(p || '')),
isConfigured: async () => mockWhatsApp.configured,
@@ -0,0 +1,113 @@
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): STOP to the church's WhatsApp number means no
// WhatsApp from any of its products: kept by number and per account, checked before every send,
// passed on to Accounts, and turned back on there (or by START without Accounts).
jest.mock('../src/config/db', () => ({
user: { findFirst: jest.fn(), updateMany: jest.fn() },
whatsAppStop: { findUnique: jest.fn(), upsert: jest.fn(), deleteMany: jest.fn() },
appSetting: {
findMany: jest.fn().mockResolvedValue([{ key: 'WAWP_ACCESS_TOKEN', value: 'token' }, { key: 'WAWP_INSTANCE_ID', value: 'HOPE01' }]),
findUnique: jest.fn().mockResolvedValue({ value: 's3cret' }),
upsert: jest.fn().mockResolvedValue({}),
},
}));
jest.mock('axios', () => ({ post: jest.fn().mockResolvedValue({ data: {} }) }));
jest.mock('../src/accounts/whatsappOptOut', () => ({ stopInAccounts: jest.fn().mockResolvedValue(true), accountPageUrl: jest.fn() }));
jest.mock('../src/utils/settingsCache', () => ({ getSettingSync: () => 'Hope Family Church' }));
jest.mock('../src/utils/privacy', () => ({ ...jest.requireActual('../src/utils/privacy'), whatsAppStop: jest.fn().mockResolvedValue('account') }));
jest.mock('../src/utils/encryption', () => ({ encrypt: (v) => v, decrypt: (v) => v }));
const prisma = require('../src/config/db');
const axios = require('axios');
const { stopInAccounts, accountPageUrl } = require('../src/accounts/whatsappOptOut');
const privacy = require('../src/utils/privacy');
const stop = require('../src/utils/whatsappStop');
const { sendText } = require('../src/utils/whatsapp');
const { handleWebhook } = require('../src/controllers/whatsappController');
beforeEach(() => {
jest.clearAllMocks();
prisma.whatsAppStop.findUnique.mockResolvedValue(null);
prisma.user.findFirst.mockResolvedValue(null);
accountPageUrl.mockResolvedValue('https://accounts.hope.test/account');
});
const res = () => ({ status() { return this; }, json() { return this; } });
/** WAWP's message event, through the real handler (which answers first, then works). */
async function wawp(body, from = '27821234567@c.us', secret = 's3cret') {
await handleWebhook({ query: { secret }, body: { event: 'message', payload: { from, body, fromMe: false } } }, res());
}
const sentTexts = () => axios.post.mock.calls.filter(([url]) => url.endsWith('/send/text')).map(([, b]) => ({ to: b.chatId, text: b.message }));
describe('isWhatsAppStopped', () => {
test('a number that replied STOP here', async () => {
prisma.whatsAppStop.findUnique.mockResolvedValueOnce({ phone: '27821234567' });
expect(await stop.isWhatsAppStopped('082 123 4567')).toBe(true);
expect(prisma.whatsAppStop.findUnique).toHaveBeenCalledWith({ where: { phone: '27821234567' } });
});
test('an account Accounts says opted out, however its number is written', async () => {
prisma.user.findFirst.mockResolvedValueOnce({ id: 'u1' });
expect(await stop.isWhatsAppStopped('+27821234567')).toBe(true);
expect(prisma.user.findFirst.mock.calls[0][0].where).toEqual({ whatsappOptedOut: true, phoneNumber: { in: ['27821234567', '+27821234567', '0821234567'] } });
});
test('anyone else, and numbers WhatsApp can\'t reach', async () => {
expect(await stop.isWhatsAppStopped('0821234567')).toBe(false);
expect(await stop.isWhatsAppStopped('not a number')).toBe(false);
});
});
describe('every send checks it', () => {
test('nothing goes to a stopped number', async () => {
prisma.whatsAppStop.findUnique.mockResolvedValue({ phone: '27821234567' });
expect(await sendText('0821234567', 'Reminder: Youth Camp starts tomorrow')).toBe(false);
expect(axios.post).not.toHaveBeenCalled();
});
test('other numbers are sent to as before', async () => {
await sendText('0829999999', 'Hello');
expect(sentTexts()).toEqual([{ to: '27829999999@c.us', text: 'Hello' }]);
});
});
describe('a STOP reply', () => {
test('is kept, turns news off, goes to Accounts, and is answered once with how to undo it', async () => {
await wawp('Stop');
expect(prisma.whatsAppStop.upsert.mock.calls[0][0].create).toMatchObject({ phone: '27821234567', keyword: 'STOP', source: 'events' });
expect(prisma.user.updateMany).toHaveBeenCalledWith({ where: { phoneNumber: { in: ['27821234567', '+27821234567', '0821234567'] } }, data: { whatsappOptedOut: true } });
expect(privacy.whatsAppStop).toHaveBeenCalledWith('27821234567');
expect(stopInAccounts).toHaveBeenCalledWith('27821234567', 'Stop');
const [reply] = sentTexts();
expect(reply.to).toBe('27821234567@c.us');
expect(reply.text).toMatch(/won't get WhatsApp messages from Hope Family Church/);
expect(reply.text).toContain('https://accounts.hope.test/account');
});
test('Afrikaans STOPP and UITTEKEN count; other messages, groups and a wrong secret don\'t', async () => {
await wawp('STOPP');
await wawp('uitteken');
expect(stopInAccounts).toHaveBeenCalledTimes(2);
jest.clearAllMocks();
await wawp('Thanks for the reminder!');
await wawp('STOP', '1203630@g.us');
await wawp('STOP', '27821234567@c.us', 'wrong');
expect(prisma.whatsAppStop.upsert).not.toHaveBeenCalled();
expect(stopInAccounts).not.toHaveBeenCalled();
});
});
describe('START', () => {
test('without Accounts: WhatsApp back on for the number', async () => {
accountPageUrl.mockResolvedValue(null);
await wawp('START');
expect(prisma.whatsAppStop.deleteMany).toHaveBeenCalledWith({ where: { phone: '27821234567' } });
expect(prisma.user.updateMany).toHaveBeenCalledWith({ where: { phoneNumber: { in: ['27821234567', '+27821234567', '0821234567'] } }, data: { whatsappOptedOut: false } });
expect(sentTexts()[0].text).toMatch(/back on/);
});
test('with Accounts: only a pointer to the account page (Accounts keeps the opt-out)', async () => {
await wawp('start');
expect(prisma.whatsAppStop.deleteMany).not.toHaveBeenCalled();
expect(sentTexts()[0].text).toContain('https://accounts.hope.test/account');
});
});
+36 -1
View File
@@ -1,5 +1,11 @@
# Handover — where things stand and how to carry on
> **2026-11-30:** Events is now at **3.8.0** (released, not deployed; 3.7.2 is rolled out). Where
> it stands and what's next is kept in the root [HANDOVER.md](../../../docs/HANDOVER.md) and
> [VERSIONS.md](../../../docs/VERSIONS.md); this file keeps the "where the code lives" notes.
> Changed since the note below: STOP stops all WhatsApp (see "Where WhatsApp STOP lives (3.8.0)")
> and the demo has the eight demo scenarios (see "Demo data").
Last updated: 2026-11-18, after **2.3.1** (Next.js 16.4.6 for security advisories, on top of 2.3.0;
released, not deployed yet; servers still run 2.1.1 until they're adopted, see the root
[ROLLOUT-1.0.md](../../../docs/ROLLOUT-1.0.md)).
@@ -263,7 +269,8 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
`CommunicationConsent`), unsubscribe tokens (HMAC with `JWT_SECRET`, never expire),
`filterRecipients` (every bulk send goes through it: `kind` 'update' passes, 'news' only to
opted-in accounts and not to `MessagingOptOut` addresses), email/WhatsApp footers, STOP
handling, data requests, `deletionBlockers`, `anonymiseUser`, `exportUserData` + PDF.
handling (news off; from 3.8.0 all WhatsApp too, below), data requests, `deletionBlockers`,
`anonymiseUser`, `exportUserData` + PDF.
Tests: `backend/tests/privacy.test.js`; e2e: `e2e/privacy.spec.ts`.
- `controllers/privacyController.js` + `routes/privacyRoutes.js` (`/api/privacy`).
- Bulk sends: `broadcastController`, `whatsappBroadcastController`, and `emailEventAttendees` /
@@ -472,6 +479,22 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
- Frontend: `components/admin/WebhooksTab.tsx`. Tests: `tests/webhooks.test.js`, e2e
`webhooks.spec.ts` (runs a receiver on localhost:5199; e2e backend has `WEBHOOKS_ALLOW_PRIVATE`).
## Where WhatsApp STOP lives (3.8.0)
- APP-1.0-PLAN decision 11: STOP to the church's WhatsApp number stops **all** WhatsApp from every
one of the church's products (event updates, tickets, kids messages, 2FA codes), not only news.
- `src/utils/whatsappStop.js`: `isWhatsAppStopped` (by number in `WhatsAppStop`, or an account with
`User.whatsappOptedOut`, set from Accounts' `user.updated` `whatsapp_opted_out`), `recordStop`,
`clearStop`, `isStartKeyword`. `sendText` / `sendPdf` (`utils/whatsapp.js`) check it before every
message; only the reply that confirms a STOP is sent anyway (`evenIfStopped`). 2FA codes for a
stopped number go by email (`utils/twoFactor.js`).
- The webhook (`handleIncomingMessage`): STOP → kept, news off (`privacy.whatsAppStop`), passed on to
Accounts (`src/accounts/whatsappOptOut.ts`, `whatsapp.optout`); the reply links Accounts' account
page. START turns it back on only without Accounts (with Accounts it's turned on there, and
`updateLocalCopy` clears this site's STOP for the number).
- **Anything new that sends WhatsApp** goes through `sendText` / `sendPdf`, never WAWP directly.
- Tests: `tests/whatsappStop.test.js`, `tests/accountsWhatsappOptOut.test.ts`.
## Demo data (1.48.2)
- `backend/scripts/set-demo.js` builds everything in memory and writes it with `createMany` in one
@@ -486,6 +509,14 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
- Tried by seeding all four into a throwaway database and calling the API (events, series page and
report, season pass, kids board, roster, attendance registers, certificate check, cashups, campus
scoping).
- **3.8.0, the demo scenarios** (APP-1.0-PLAN §12): `PROFILES` also has one per scenario
(`agent.DEMO_SCENARIOS`), each a copy of one of the four kinds (`SCENARIO_KINDS`) built around
the scenario's church from `@crosscode/demo`: its people (`buildScenarioPeople`: leads become the
staff, at most 260 members), its campuses (`buildCampuses`), its staff as event contacts
(`staffName`). Builders stop when a small church runs out of people (`nextBuyer` returns null),
so don't add one that needs a fixed number of people without the same guard. The scenario's
own people are never sent to `people.removeDemo` (Accounts loaded them first). All eight and
the four were loaded into a throwaway PostgreSQL 18 database before release.
## Where the dashboard and palette live (1.49.0)
@@ -745,6 +776,10 @@ Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md
into WAWP (events `message` + `session.status`), and only for senders WhatsApp identifies by
phone number — a sender known only by a "LID" is logged and ignored (they can still use the
link in the message).
- (3.8.0) No test yet for a 2FA code falling back to email for a number that replied STOP.
- (3.8.0) The demo scenarios reuse the four demos' events: a scenario's own events (Grace
Cathedral's concert series, Ignite's youth conference) and Afrikaans content for Karoo
Gemeenskapskerk aren't built yet.
- There's no log of individual messages sent, so "Download my data" can't include "messages
sent to you" yet.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.7.1",
"version": "3.9.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -26,6 +26,7 @@ import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { uploadImage } from "@/lib/eventSetup";
import { useExternalEffect } from "@/lib/hooks";
import { useChurch } from "@/contexts/ChurchContext";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai";
@@ -48,7 +49,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
];
const inputCls =
"w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
"w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500";
/** The code from Search Console's verification meta tag; accepts the whole tag or just the code. */
function googleVerificationCode(input: string): string {
@@ -56,6 +57,20 @@ function googleVerificationCode(input: string): string {
return (m ? m[1] : input).trim();
}
/**
* Shown above Organisation and Branding while the church's Accounts sets some of their fields:
* those come from the church profile (on all the church's sites) and are changed there.
*/
function FromAccountsNotice({ what, href }: { what: string; href: string | null }) {
return (
<div className="rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-900">
Your church&apos;s {what} come from its church profile in Accounts, so every one of its sites shows the same.
They can&apos;t be changed here.{" "}
{href ? <a href={href} className="font-medium underline">Change them in Accounts ↗</a> : "Change them in Accounts, under Church profile."}
</div>
);
}
function Field({
label, hint, required, children,
}: {
@@ -146,6 +161,14 @@ function SiteSettingsPageInner() {
const [faviconPreview, setFaviconPreview] = useState<string | null>(null);
const faviconRef = useRef<HTMLInputElement>(null);
// ── From Accounts ── the settings the church profile sets (name, logo, colours, contact): shown,
// not editable, and never sent back. The church profile's own page in Accounts changes them.
const [managed, setManaged] = useState<Set<string>>(new Set());
const church = useChurch();
const accountsChurchUrl = church ? `${church.links.accounts.replace(/\/+$/, "")}/admin/church` : null;
const fromAccounts = (key: string) => managed.has(key);
const ownOnly = (updates: Record<string, string>) => Object.fromEntries(Object.entries(updates).filter(([k]) => !managed.has(k)));
// ── Notifications ──
const [notifEmails, setNotifEmails] = useState("");
@@ -206,6 +229,7 @@ function SiteSettingsPageInner() {
setLegalEffectiveDate(s.legal_effective_date || "");
setConsentRetentionDays(s.consent_medical_retention_days || "30");
setNotifyOnImpersonation(s.notify_user_on_impersonation === "true");
setManaged(new Set((s.accounts_managed || "").split(",").filter(Boolean)));
})
.catch((e: unknown) => setResult({ ok: false, message: errorMessage(e) || "Failed to load settings" }))
.finally(() => setLoadingInitial(false));
@@ -220,7 +244,7 @@ function SiteSettingsPageInner() {
setSaving(true);
setResult(null);
try {
await apiV2Data("put", "/settings", { authToken: token, body: updates });
await apiV2Data("put", "/settings", { authToken: token, body: ownOnly(updates) });
setResult({ ok: true, message: "Saved." });
reloadSettings();
} catch (e) {
@@ -271,13 +295,13 @@ function SiteSettingsPageInner() {
await apiV2Data("put", "/settings", {
authToken: token,
body: {
body: ownOnly({
primary_color: primaryColor,
secondary_color: secondaryColor,
accent_color: accentColor,
logo_url: finalLogoUrl,
favicon_url: finalFaviconUrl,
},
}),
});
setLogoUrl(finalLogoUrl);
setLogoFile(null);
@@ -303,13 +327,13 @@ function SiteSettingsPageInner() {
try {
await apiV2Data("put", "/settings", {
authToken: token,
body: { primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" },
body: ownOnly({ primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" }),
});
setPrimaryColor("#4F46E5");
if (!fromAccounts("primary_color")) setPrimaryColor("#4F46E5");
setSecondaryColor("#8B5CF6");
setAccentColor("#EC4899");
setLogoUrl(""); setLogoFile(null); setLogoPreview(null);
setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null);
if (!fromAccounts("accent_color")) setAccentColor("#EC4899");
if (!fromAccounts("logo_url")) { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); }
if (!fromAccounts("favicon_url")) { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); }
setSuggestedColors([]);
setResult({ ok: true, message: "Reset to defaults." });
reloadSettings();
@@ -433,9 +457,10 @@ function SiteSettingsPageInner() {
{activeTab === "organisation" && (
<div className="space-y-4">
<h2 className="text-lg font-semibold text-gray-900">Organisation details</h2>
{["org_name", "org_email", "org_phone", "org_address"].some(fromAccounts) && <FromAccountsNotice what="name and contact details" href={accountsChurchUrl} />}
<Field label="Organisation name" required>
<input className={inputCls} placeholder="Your Organisation"
value={orgName} onChange={e => setOrgName(e.target.value)} />
value={orgName} disabled={fromAccounts("org_name")} onChange={e => setOrgName(e.target.value)} />
</Field>
<Field label="Tagline">
<input className={inputCls} placeholder="Connecting community through events"
@@ -444,16 +469,16 @@ function SiteSettingsPageInner() {
<div className="grid sm:grid-cols-2 gap-4">
<Field label="Contact email">
<input type="email" className={inputCls} placeholder="admin@yourchurch.org"
value={orgEmail} onChange={e => setOrgEmail(e.target.value)} />
value={orgEmail} disabled={fromAccounts("org_email")} onChange={e => setOrgEmail(e.target.value)} />
</Field>
<Field label="Phone">
<input className={inputCls} placeholder="+27 12 345 6789"
value={orgPhone} onChange={e => setOrgPhone(e.target.value)} />
value={orgPhone} disabled={fromAccounts("org_phone")} onChange={e => setOrgPhone(e.target.value)} />
</Field>
</div>
<Field label="Address" hint="Used as the default location for new events.">
<input className={inputCls} placeholder="123 Church St, City"
value={orgAddress} onChange={e => setOrgAddress(e.target.value)} />
value={orgAddress} disabled={fromAccounts("org_address")} onChange={e => setOrgAddress(e.target.value)} />
{orgAddress.trim() && (
<a href={mapsSearchUrl(orgAddress.trim())} target="_blank" rel="noopener noreferrer"
className="inline-block text-xs text-brand-600 hover:underline mt-1">
@@ -477,14 +502,15 @@ function SiteSettingsPageInner() {
{activeTab === "branding" && (
<div className="space-y-5">
<h2 className="text-lg font-semibold text-gray-900">Branding</h2>
{["primary_color", "accent_color", "logo_url", "favicon_url"].some(fromAccounts) && <FromAccountsNotice what="logo and colours" href={accountsChurchUrl} />}
<div className="grid sm:grid-cols-3 gap-4">
<ColorPickerField label="Primary" hint="Buttons, links, nav highlights, and the email header/CTA."
value={primaryColor} onChange={setPrimaryColor} />
value={primaryColor} onChange={setPrimaryColor} disabled={fromAccounts("primary_color")} />
<ColorPickerField label="Secondary" hint="Subtle backgrounds and outline-button borders/text."
value={secondaryColor} onChange={setSecondaryColor} />
<ColorPickerField label="Accent" hint="Hover states and highlight chips/badges."
value={accentColor} onChange={setAccentColor} />
value={accentColor} onChange={setAccentColor} disabled={fromAccounts("accent_color")} />
</div>
<Field label="Site logo" hint="PNG, JPG, SVG or WebP, max 2 MB. Displayed in the navigation bar.">
@@ -492,16 +518,16 @@ function SiteSettingsPageInner() {
<div className="mb-3 flex items-center gap-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={currentLogoSrc} alt="Current logo" className="h-16 object-contain border rounded p-1 bg-gray-50" />
<button
{!fromAccounts("logo_url") && <button
type="button"
className="text-xs text-red-500 hover:text-red-700"
onClick={() => { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); setSuggestedColors([]); if (fileRef.current) fileRef.current.value = ""; }}
>
Remove
</button>
</button>}
</div>
)}
<input ref={fileRef} type="file" accept="image/*" onChange={e => handleLogoFileChange(e.target.files?.[0])} className="text-sm" />
{!fromAccounts("logo_url") && <input ref={fileRef} type="file" accept="image/*" onChange={e => handleLogoFileChange(e.target.files?.[0])} className="text-sm" />}
{suggestedColors.length > 0 && (
<div className="mt-3 border rounded-lg p-3 bg-gray-50">
<p className="text-xs font-medium text-gray-600 mb-2">Suggested from your logo — click a swatch to apply it</p>
@@ -524,21 +550,21 @@ function SiteSettingsPageInner() {
<div className="mb-3 flex items-center gap-3">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={currentFaviconSrc} alt="Current favicon" className="h-8 w-8 object-contain border rounded p-1 bg-gray-50" />
<button
{!fromAccounts("favicon_url") && <button
type="button"
className="text-xs text-red-500 hover:text-red-700"
onClick={() => { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); if (faviconRef.current) faviconRef.current.value = ""; }}
>
Remove
</button>
</button>}
</div>
)}
<input ref={faviconRef} type="file" accept=".ico,.png,.svg,image/x-icon,image/png,image/svg+xml" onChange={e => {
{!fromAccounts("favicon_url") && <input ref={faviconRef} type="file" accept=".ico,.png,.svg,image/x-icon,image/png,image/svg+xml" onChange={e => {
const file = e.target.files?.[0];
if (!file) return;
setFaviconFile(file);
setFaviconPreview(URL.createObjectURL(file));
}} className="text-sm" />
}} className="text-sm" />}
</Field>
<div className="flex items-center justify-between pt-4 border-t mt-6 flex-wrap gap-3">
@@ -5,12 +5,14 @@ import { isValidHex } from "@/lib/colorScale";
/** A native color swatch + hex text input, shared by the admin Branding tab and the setup wizard's Branding step. */
export function ColorPickerField({
label, hint, value, onChange,
label, hint, value, onChange, disabled,
}: {
label: string;
hint?: string;
value: string;
onChange: (hex: string) => void;
/** Set elsewhere (the church profile in Accounts): shown, not changed here. */
disabled?: boolean;
}) {
const valid = isValidHex(value);
return (
@@ -19,13 +21,15 @@ export function ColorPickerField({
<div className="flex items-center gap-3">
<input
type="color"
className="h-10 w-20 border rounded cursor-pointer shrink-0"
disabled={disabled}
className="h-10 w-20 border rounded cursor-pointer shrink-0 disabled:cursor-not-allowed"
value={valid ? value : "#000000"}
onChange={e => onChange(e.target.value)}
/>
<input
className={`w-full border rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 ${valid ? "" : "border-red-300"}`}
className={`w-full border rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500 ${valid ? "" : "border-red-300"}`}
placeholder="#2563eb"
disabled={disabled}
value={value}
onChange={e => onChange(e.target.value)}
/>
+6 -3
View File
@@ -52,15 +52,18 @@ function computeApiBase(): string {
export const API_BASE = computeApiBase();
// Resolve a URL or path to use the API origin. If it's a relative path, prefix with API_BASE.
// If it's an absolute URL but points to localhost/127.0.0.1/::1, rewrite its origin to API_BASE.
// If it's an absolute URL to this site's own uploads on localhost/127.0.0.1/::1, rewrite its
// origin to API_BASE. Another localhost address (the church's Accounts in development, whose logo
// the site now shows) is left as it is.
export function resolveToApiOrigin(urlOrPath: string | null | undefined): string | null {
const raw = (urlOrPath || "").trim();
if (!raw) return null;
try {
if (raw.startsWith("http")) {
const u = new URL(raw);
const isLocal = ["localhost", "127.0.0.1", "::1"].includes(u.hostname);
if (isLocal && API_BASE) {
const isLocal = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname);
const ownUpload = /^\/(api\/)?uploads\//.test(u.pathname);
if (isLocal && ownUpload && API_BASE) {
const api = new URL(API_BASE);
u.protocol = api.protocol;
u.hostname = api.hostname;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.7.1",
"version": "3.7.2",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+236
View File
@@ -1,5 +1,241 @@
# Changelog — Church Website
## [1.9.0] — 2026-12-01
No migration, no new environment settings. Needs `@crosscode/ui` 0.4.0 (built with the Website).
### Added
- **A background for each homepage section** (Template and style → Home page layout), from the
church's colours: as the style sets it (the default), white, soft main colour, soft accent
colour, main colour, or deep main colour. Stored on the design's home entry (`background`,
`SECTION_BACKGROUNDS` in `src/site/variants.ts`), kept through a template switch, checked by
`cleanDesign`, and carried to the snapshot's section. On the main colour, text, links and
buttons use the palette's on-brand colour; on the deep shade, white. A layout with its own
background (`cc-own-bg`: a photo, a band) and the top of the page keep theirs; Section colour's
tinted and mixed patterns skip a section that has its own.
### Changed
- **Events from Cross Events** say "Register on our Events site" only when they take
registrations and are open; contact-only, full or closed ones say "More info on our Events
site". The site's events carry the registration's `mode`.
- **Church details:** the main and accent colours use the shared colour field (`ColourField`,
`@crosscode/ui` 0.4.0): a swatch, the hex code to type or paste, and a preview, as Cross Events'
Branding settings.
## [1.8.0] — 2026-11-30
No migration, no new environment settings. The backend now uses `@crosscode/demo` (built by
`crosscode deploy` with the other shared packages).
### Added
- **Demo scenarios** (APP-1.0-PLAN §12): `npm run demo -- --profile <p> --scenario <p>` (the
scenario must be the profile of the same name) loads a profile as part of the scenario, so the
Website shows the same church as Accounts, Cross Events and the App.
- **Leaders:** each profile's `scenarioTeam` (`src/demo/seeds.ts`) names four parts, roles and
portraits, the pastor first; the names are the scenario's people from `demoPeople`. The pastor
is the home page's pastor and the messages' speaker, and every portrait's alt text is the new
name. None of the profile's own leader names is left.
- **Events:** with a linked Cross Events, a scenario load makes no simple events of its own (and
no pictures for them), turns on that link's **Show events from** and fetches Events' whole
feed at once (`syncLink`, full), so Events' events show, never copied. If Events can't be
reached the load still succeeds and says so; the 15-minute sync catches up. Without Events, the
profile's own three events, as before.
- On a site with no church profile at all, a scenario saves the scenario's church (from
`@crosscode/demo`) instead of Acacia Hill.
- `crosscode demo <church> website --profile <p> --scenario <p>` passes `--scenario` on (agent
1.7.0 sends it for the Hub's **Load a demo scenario**) and refuses a release before 1.8.0;
`packages/demo` joins the Website's shared packages (`website_shared_packages`,
`website_build`).
## [1.7.1] — 2026-11-28
One migration (`20261128000000_photo_framing`: a nullable `framing` column on `Ministry`,
`Leader` and `SimpleEvent`), run by `crosscode deploy`. No new environment settings.
### Fixed
- **Move and zoom everywhere a photo is framed, not only in page sections.** 1.7.0 had it in the
page editor only. Ministries, Leadership and Events now have the same **Move and zoom** on their
photo, shown in the frame the site uses for the current template and layouts (`frameFor` types
`ministry`, `leader`, `event`; `RowFraming` in `admin/framing.tsx`). It's saved with the row as
`framing` (`{ x, y, zoom }`, null for centred) and cleared when the photo is removed or changed.
Ministries and leaders are drafts until Publish (in the snapshot, Discard and Restore, as
`image.focus` / `photo.focus`); an event's shows once the event is published, like the rest of
it. Versions published before this compare unchanged (no framing key), so nothing shows as a
pending change after the update.
## [1.7.0] — 2026-11-27
No migration, no new environment settings.
### Added
- **Move and zoom a photo in its frame.** In a section's form (the top of the page, Welcome,
Invitation, Image and text), a chosen photo shows in the shape of the frame the site puts it in
for the current template and layout (`admin/framing.tsx`, `frameFor`), with **Move and zoom**:
drag (or arrow keys) to choose what stays in view, zoom up to 300% to crop closer, Reset. It's
saved with the section as `data.framing` (by media id: `{ x, y, zoom }`), so it's a draft
like any other edit: the live preview shows it on Save, visitors after Publish. The site draws it
with `object-position` and `scale()` around the same point (`focusStyle` in `site/parts.tsx`);
the Bold split and collage frames now clip (`overflow-hidden`), and a zoomed photo in a
Heritage frame stays inside its mat. Framing for a photo the section no longer shows is dropped
when it's saved.
- **Delete photos from the media library.** Each photo says where it's used (draft pages and
their sections, ministries, leaders, series, events, the site icon, the live site, the church's
logo); one used nowhere has **Delete** (Editors and up), which removes the row and its files
(the photo and its responsive sizes, never outside the uploads folder) and frees the storage.
`DELETE /api/v1/admin/media/:id` refuses one in use (409 `IN_USE`, saying where); audited as
`media_deleted`.
## [1.6.1] — 2026-11-27
No migration, no new environment settings.
### Fixed
- **Events from Cross Events no longer show twice after Events is reseeded.** After the first
fetch, the Website only asked for what changed (`?updatedSince=`) and dropped a copy only when
the feed listed it in `deleted`. A reseed (or a restore) gives every event a new id without
listing the old ones, so the old copies stayed beside the new. The 15-minute poll and "Sync now"
now fetch the whole list and drop copies that aren't in it (`syncLink(…, { full: true })`); the
fetch after an `event.changed` still asks only for what changed.
- **Loading a demo (`npm run demo`, `crosscode demo … website`) tells Cross Events.** The old
published events go into the feed's `deleted` (`FeedRemoval`) and linked products get an
`event.changed`, so Events drops its copies straight away instead of showing them beside the
new ones.
### Changed
- **The header's links to the church's other sites say so:** "Events site" with an external-link
icon (title "Our separate site"), instead of "Events", which looked like a second link to this
site's own Events page.
## [1.6.0] — 2026-11-27
No migration, no new environment settings.
### Changed
- **The demo church has photos** instead of the generated "hills and sun" illustration that
stood in for every picture. 104 stock photos from Unsplash (free under the Unsplash License;
credits in `backend/demo-photos/CREDITS.md` and `photos.json`), 12 MB of WebP in
`backend/demo-photos/`. Each demo profile has its own set (`photos` in `src/demo/seeds.ts`): a
stone parish church, a city spire, a worship night, a school hall, a family table, farmland, a
coffee table, a campus. The ministry pictures match what they are (Sunday school, choir, soup
kitchen, students). Acacia Hill (a template on its own) gets an acacia at sunrise. The people
are the photographers' models.
- **Every leader has a portrait** (before: only the first, so the team showed three empty
circles), named for them in its alt text (`photos.team`).
- **The demo's events have pictures** (`photos.events`; before: the grey placeholder on event
cards). Photos that compress well where an event page shows them large (the picnic is 75 KB at
960 px, not the 170 KB of the busier one), so the event pages stay at Lighthouse 90+.
- **The demo's messages have photos** (`photos.messages`: a pulpit, an open Bible, a
microphone, a preacher who matches the speaker) instead of the stand-in video's thumbnail.
`Message.thumbnailUrl` set to one of the site's own uploads (`/api/uploads/…`) now comes before
the YouTube thumbnail (`messageThumbnail`); admins and the YouTube feed store YouTube's address
there, which is still never used, so nothing changes for a church's own messages.
- Demo photos become media assets the way an upload does (`processImage`: 480, 960 and 1600 px
in WebP and JPEG), so demo sites serve responsive images. Each photo is processed once per
machine (`<tmp>/crosscode-website-demo/`, made in a folder of its own and renamed into place)
and copied into `<uploads>/demo/`. Without `demo-photos/`, the illustration still stands in.
- e2e: the fake YouTube thumbnail is one of the demo photos.
### Fixed
- Photos in small frames are fetched at their size, not the screen's: Community's collage hero
(fixed 10–16rem frames), the collage row in the other templates (a third of the width), the
team's portraits (12rem, 20rem featured) and the ministry cards (a quarter or a third of the
width) say so in `sizes`. A phone fetched the 960 or 1600 px photo for each before.
## [1.5.0] — 2026-11-27
No migration, no new environment settings.
### Added
- **Backups of the photos and files** (`src/backups/uploads.ts`): the nightly `backup` job (and
Back up now) makes, after the database backup, a snapshot of the uploads in
`backend/backups/uploads-YYYYMMDD-HHMMSS/`. A file the same as in the last snapshot (size and
time) is a hard link to it; the rest is copied, keeping its time. Uploads never change once
made, so after the first full copy each night costs only the new files, and each snapshot is
still a real copy: deleting or damaging a file in `uploads/` leaves the snapshots alone.
`.thumbnails` and other dot entries are left out. Built in a `.uploads-…-partial` folder and
renamed when complete (a leftover partial is removed on the next run). Refused before copying
anything when the disk hasn't room for what's new. Each holds a `.snapshot.json` (files, bytes,
new files, new bytes). The newest `backup_retain_count` are kept, as the database backups.
Off with `backup_uploads` = false; the last failure in `backup_uploads_last_error`. To put
them back: `cp -a backups/uploads-…/. uploads/` as the site's user.
- **Admin → Backups:** "Include the photos and files" (saved with the other backup settings), the
snapshots (when, files, size, new since the one before), and their last failure. Back up now
makes both and says if only the database worked.
### Changed
- The `backup` job is "Backup: the database, and the photos and files". The database backup is
made even when the uploads' fails; the job then fails, so its run and the Hub show it.
## [1.4.0] — 2026-11-27
No migration: pg-boss makes its own schema (`pgboss_website`) on first start, as in Accounts. New
dependencies `pg-boss` and `cron-parser`. Needs `pg_dump` on the server (it's there: the
crosscode script uses it for the backups before updates).
### Added
- **Database backups** (`src/backups/backups.ts`, as Accounts 1.3.0): a gzipped `pg_dump` into
`backend/backups/` every night at 02:20 (after Accounts' at 02:00 on the same server) and when an
admin asks; the newest 14 kept (`backup_retain_count`), nightly on by default
(`backup_nightly`), the last failure in `backup_last_error`. Same names as the crosscode
script's backups before updates (`website-YYYYMMDD-HHMMSS.sql.gz`), so the list shows both. A
dump that fails part-way leaves no file. The database only: the uploads aren't in it (as Events).
- **Admin → Backups** (Owners and Admins): back up now, download one (audited, never cached), turn
nightly backups off, how many to keep. `GET /api/v1/admin/backups`, `POST …/backups/run`,
`PUT …/backups/settings`, `GET …/backups/:file/download`.
- **Background jobs on pg-boss** (`src/jobs.ts`, as Accounts 1.4.0): `backup`, `hub-heartbeat`
(every 15 minutes), `event-feed` (every 15 minutes) and `youtube` (hourly). One run per
schedule however many processes run; timers in the process if the queue can't start;
`JOBS_ENABLED=false` turns them all off. Per job: its .env flag (`BACKUP_ENABLED`,
`HUB_HEARTBEAT_ENABLED`, `FEED_JOB_ENABLED`, `YOUTUBE_JOB_ENABLED`) and `JOB_SCHEDULE_<NAME>`.
- **Admin → Background jobs** (Owners and Admins): each job's schedule, next run and last runs;
switch it on or off, change its schedule (kept in `job_overrides`, winning over the .env, live
at once), or run it now. Audited (`job_settings_changed`, `job_run`).
### Changed
- **The heartbeat reports the newest backup** (`lastBackupAt`; before always null, so the Hub
showed "No backup reported" on every Website) **and the real job mode and failed runs in the
last 24 hours** (before always "queue" and 0).
- The heartbeat, the event feed and YouTube were plain timers (`startHeartbeats`,
`startFeedSync`, `startYoutubeSync`, removed); they're jobs now. The first event-feed and
YouTube runs are on their schedule rather than 20 and 30 seconds after a start.
## [1.3.0] — 2026-11-27
No migration, no new environment settings. Needs contracts 1.19.0 (in this checkout).
### Added
- **Eight demo churches**, two per template, for the Hub's demo sites (Hub 2.25.0, agent 1.6.0,
`crosscode demo <church> website --profile <p>`): `heritage-parish`, `heritage-city`,
`bold-youth`, `bold-plant`, `community-family`, `community-town`, `clean-modern`,
`clean-campus` (`src/demo/seeds.ts`, ids from contracts `agent.WEBSITE_DEMO_PROFILES`). Each is
its own kind of church: home page, Plan your visit, About, Give, four ministries, four leaders, a
message series with three messages, and three upcoming events. The second of each template starts
on the template's second recommended variant of every homepage section and its second header, so
the eight show every recommended look.
- **They keep the organisation settings:** a profile replaces the content only. The church's
profile (from Accounts, else `church_profile_local`) stays, the copy names the church
(`{name}`, `{short}`, `{city}`) and the illustrations use its colours. The site settings, the
site icon (`favicon_media_id` and its picture) and the admins stay. Acacia Hill's profile is
saved only on a site with no profile at all, so it still has a name. Slug history and preview
links go with the old content.
- `npm run demo -- --profile <p> [--force]` and `--list`. `--template <t>` alone still loads the
Acacia Hill development church exactly as before (its profile too), so the e2e suite and its
screenshots are unchanged.
## [1.2.0] — 2026-11-27
No migration, no new environment settings. Its first start on an existing site adds the missing
+69
View File
@@ -3,6 +3,75 @@
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.9.0
- **Choose a background for each homepage section.** In **Template and style → Home page layout**,
each section now has a background in your church's colours: white, a soft wash of your main or
accent colour, your main colour, or a deep shade of it. Text and buttons change to stay easy to
read. Leave it as it is and the section follows your style's section colour, as before.
- **Events say "More info" when there's nothing to register for.** An event from your Events site
only says "Register on our Events site" when people can register; events where people just
contact the church say "More info on our Events site".
- **An easier colour picker** in **Church details**: pick a colour, or type or paste its code
(like #1f4e79), and see it straight away.
## 1.8.0
- Behind the scenes, Cross Code's demonstration websites can now be loaded as part of a whole demo
church, with the same people and events as its Accounts, Events site and App. Nothing changes on
your own website.
## 1.7.1
- **Move and zoom now works for ministries, your team and events too**, not only for page
sections. Edit a ministry, a person or an event, and press **Move and zoom** on its photo.
Ministries and people show it on your site once you publish; an event shows it once the event
is published.
## 1.7.0
- **Move and zoom your photos.** When you choose a photo for a section, you now see it in the
shape it has on your site. Press **Move and zoom** to drag it so the right part shows (faces,
not the ceiling) and zoom in to crop closer. Save, and the preview shows it; publish, and
visitors see it.
- **Delete photos you don't need.** In the **Media library**, each photo says where it's used.
Photos that aren't used anywhere have a **Delete** button, which frees up their storage.
## 1.6.1
- **The link to your Cross Events site is easier to tell apart** in your website's menu: it now
says "Events site" with a small arrow icon, so visitors don't mistake it for your website's own
Events page.
- **Fixed: events from Cross Events could show twice** after the Events site's data was replaced.
Your website now checks the full list every 15 minutes and removes events that are gone.
## 1.6.0
- **Photos load faster on phones.** Photos in small frames (the collage at the top of the
Community template, your team's portraits and the ministry cards) are now downloaded at the size
they're shown, instead of full width. Nothing to change on your side.
- Behind the scenes, Cross Code's demonstration websites now show real photos of a (made-up)
church instead of drawings.
## 1.5.0
- **Your photos and files are backed up too.** Every night, after your site's content, your media
library is backed up on the server. After the first time, only new photos and files are copied.
Under **Backups** you see each one, and can switch it off.
## 1.4.0
- **Your website is backed up every night.** A copy of your site's content is kept on the server
every night, and before every update. Owners and Admins find them under **Backups**: make one
now, download one, or choose how many to keep. Your photos and files aren't in them.
- **Background jobs:** under **Background jobs**, see what your site does on a schedule (backups,
your events from Cross Events, new videos from YouTube), and switch each one on or off.
## 1.3.0
- Nothing changes on your site. Behind the scenes, Cross Code can now load demo content on the
websites it uses for demonstrations.
## 1.2.0
- **Your home page and the other pages are there from the start:** a new website now comes with
+115
View File
@@ -0,0 +1,115 @@
# Demo photos
The demo church's photos (`src/demo/`), from [Unsplash](https://unsplash.com), used under the
[Unsplash License](https://unsplash.com/license): free to use, commercially too, without asking.
The people in them are the photographers' models, standing in for the fictional churches' people.
Credit is not required, but given here. Each is WebP, at most 2000 px wide (portraits 1000 × 1250,
cropped to the face); `photos.json` holds their alt text, size and credit, keyed by the names the
demo profiles use (`src/demo/seeds.ts`).
| Photo | Photographer | On Unsplash |
|-------|--------------|-------------|
| `acacia-sunrise` | [Damian Patkowski](https://unsplash.com/@damianpatkowski) | [T-LfvX-7IVg](https://unsplash.com/photos/tree-between-green-land-during-golden-hour-T-LfvX-7IVg) |
| `city-spire` | [Ross Sneddon](https://unsplash.com/@rosssneddon) | [2XTPV6WykVc](https://unsplash.com/photos/person-walking-on-pathway-2XTPV6WykVc) |
| `stone-church` | [Wolfgang Weiser](https://unsplash.com/@hamburgmeinefreundin) | [UCnBapalXbE](https://unsplash.com/photos/historic-brick-church-with-tall-spire-surrounded-by-trees-UCnBapalXbE) |
| `country-church` | [Vedanth Ravi](https://unsplash.com/@vedanthravi) | [ql9-rgPUPZE](https://unsplash.com/photos/old-stone-church-ruins-under-a-blue-sky-ql9-rgPUPZE) |
| `church-light` | [Debby Hudson](https://unsplash.com/@hudsoncrafted) | [sgdyBq6kheQ](https://unsplash.com/photos/cathedral-interior-sgdyBq6kheQ) |
| `church-aisle` | [BEN ELLIOTT](https://unsplash.com/@benjaminelliott) | [-_M9YXEliAI](https://unsplash.com/photos/a-large-church-with-a-large-stained-glass-window--_M9YXEliAI) |
| `church-doors` | [João Weyne Justa](https://unsplash.com/@joaoweynej) | [VCbtM1PR4_o](https://unsplash.com/photos/empty-church-pews-lead-to-a-cross-in-the-distance-VCbtM1PR4_o) |
| `church-white` | [Julia Taubitz](https://unsplash.com/@justmejuliee) | [MVE9TBMdXLs](https://unsplash.com/photos/pews-and-chandelier-in-vimmerby-church-MVE9TBMdXLs) |
| `farm-road` | [Mario Beducci](https://unsplash.com/@mariobeducci) | [sVp8eXOLovA](https://unsplash.com/photos/a-winding-dirt-road-through-rolling-hills-at-sunset-sVp8eXOLovA) |
| `farm-bales` | [Vi Bell](https://unsplash.com/@vibell) | [BZa5NqifCt8](https://unsplash.com/photos/hay-bales-in-harvested-field-BZa5NqifCt8) |
| `school-hall` | [Pix Tresa](https://unsplash.com/@pixtresa) | [qRtFqXNkssY](https://unsplash.com/photos/wooden-folding-chairs-in-paneled-room-qRtFqXNkssY) |
| `hall-chairs` | [Adolfo Félix](https://unsplash.com/@adolfofelix) | [6hSBcpa7qVI](https://unsplash.com/photos/rows-of-empty-chairs-in-a-wood-paneled-room-6hSBcpa7qVI) |
| `campus-path` | [avansear](https://unsplash.com/@avansear) | [nWyKIZVidIs](https://unsplash.com/photos/campus-path-with-trees-and-people-nWyKIZVidIs) |
| `congregation-warm` | [Christian Harb](https://unsplash.com/@c7arb) | [RAENAd2Rxoo](https://unsplash.com/photos/a-congregation-gathered-inside-a-large-hall-RAENAd2Rxoo) |
| `congregation-pews` | [Christian Harb](https://unsplash.com/@c7arb) | [e77txgeniiU](https://unsplash.com/photos/audience-seated-in-a-church-during-a-service-e77txgeniiU) |
| `congregation-modern` | [Sophie Spree](https://unsplash.com/@sophiespree) | [9zJcrli2WCU](https://unsplash.com/photos/a-group-of-people-standing-in-a-room-with-their-hands-in-the-air-9zJcrli2WCU) |
| `congregation-hall` | [Charise Pieterse](https://unsplash.com/@cedarhillchurch) | [IyGJ38BOcP8](https://unsplash.com/photos/people-standing-in-church-worship-IyGJ38BOcP8) |
| `worship-hands` | [Fallon Michael](https://unsplash.com/@fallonmichaeltx) | [bUd6kWoVfII](https://unsplash.com/photos/people-raising-their-hands-up-bUd6kWoVfII) |
| `band-stage` | [Memento Media](https://unsplash.com/@heymemento) | [PbQF8EIsR2U](https://unsplash.com/photos/man-in-black-leather-jacket-playing-guitar-PbQF8EIsR2U) |
| `band-big` | [Bree Anne](https://unsplash.com/@breebuddy) | [dDED_VZ2jbI](https://unsplash.com/photos/people-sitting-on-chairs-watching-band-performing-on-stage-dDED_VZ2jbI) |
| `band-small` | [AMONWAT DUMKRUT](https://unsplash.com/@amonwatdumkrut) | [3E0KqEVDKzg](https://unsplash.com/photos/woman-singing-in-church-worship-service-3E0KqEVDKzg) |
| `guitar-singer` | [Luke Thornton](https://unsplash.com/@lukethorntonofficial) | [JNl7o-Mj2cc](https://unsplash.com/photos/man-in-gray-v-neck-long-sleeve-shirt-playing-brown-acoustic-guitar-JNl7o-Mj2cc) |
| `guitar-room` | [Gabriel Rodrigues](https://unsplash.com/@gabrielrodriguesoficial) | [p6V49LDtWA4](https://unsplash.com/photos/a-man-sitting-on-a-chair-playing-a-guitar-p6V49LDtWA4) |
| `choir-church` | [Green Liu](https://unsplash.com/@greenliustudio) | [ZaZcvU_WuF8](https://unsplash.com/photos/a-group-of-people-singing-in-front-of-a-golden-alter-ZaZcvU_WuF8) |
| `choir-gospel` | [John Onaeko](https://unsplash.com/@iyinoluwaonaeko) | [8__esxuic9Q](https://unsplash.com/photos/group-of-people-standing-on-brown-wooden-floor-8__esxuic9Q) |
| `organ` | [Spencer Plouzek](https://unsplash.com/@theguccer2100) | [aOexpXIBH_I](https://unsplash.com/photos/man-playing-a-large-wooden-pipe-organ-aOexpXIBH_I) |
| `candles` | [Eli Solitas](https://unsplash.com/@elisolitas) | [q6e4zwgtUcM](https://unsplash.com/photos/lighted-candles-on-black-metal-candle-holder-q6e4zwgtUcM) |
| `kids-craft` | [Yosi Prihantoro](https://unsplash.com/@yosipri) | [1q2Fo7Bx-pk](https://unsplash.com/photos/a-young-girl-is-holding-a-cross-made-of-paper-1q2Fo7Bx-pk) |
| `kids-drawing` | [Ruslan Horovyi](https://unsplash.com/@ruslanstock) | [ycuGtOTAtuU](https://unsplash.com/photos/two-young-students-drawing-together-in-a-classroom-ycuGtOTAtuU) |
| `kids-teacher` | [Rewired Digital](https://unsplash.com/@rewired41) | [kPkRpy6pIIg](https://unsplash.com/photos/teacher-guiding-children-drawing-at-a-table-kPkRpy6pIIg) |
| `kids-class` | [Yegor Makarenko](https://unsplash.com/@photochel228) | [WGEgIC76RjA](https://unsplash.com/photos/adult-and-children-in-classroom-WGEgIC76RjA) |
| `toddlers` | [Amanda Costelloe](https://unsplash.com/@oliveevephoto) | [8EHfZL6rFFg](https://unsplash.com/photos/two-young-girls-playing-with-colorful-wooden-blocks-8EHfZL6rFFg) |
| `youth-group` | [Nicolas Lobos](https://unsplash.com/@lobosnico) | [AqUp2AfDgu8](https://unsplash.com/photos/people-standing-near-building-AqUp2AfDgu8) |
| `youth-outdoors` | [Elliot Krueger](https://unsplash.com/@kruegerelliot) | [qNreMakc6eU](https://unsplash.com/photos/a-group-of-people-sitting-on-a-rock-in-the-woods-qNreMakc6eU) |
| `teens` | [Eliott Reyna](https://unsplash.com/@eliottreyna) | [axTm0ee3YP4](https://unsplash.com/photos/five-persons-on-front-of-chain-link-fence-axTm0ee3YP4) |
| `meal-table` | [Jesse Vigil](https://unsplash.com/@jessevig) | [I_b1PEyg8dY](https://unsplash.com/photos/a-group-of-people-sitting-at-a-long-table-I_b1PEyg8dY) |
| `meal-friends` | [Sweet Life](https://unsplash.com/@sweetlifediabetes) | [OxkxluMeAGs](https://unsplash.com/photos/a-group-of-people-sitting-around-a-table-eating-food-OxkxluMeAGs) |
| `meal-family` | [National Cancer Institute](https://unsplash.com/@nci) | [cfGG0niafjc](https://unsplash.com/photos/group-of-person-eating-indoors-cfGG0niafjc) |
| `supper-hall` | [Sweet Life](https://unsplash.com/@sweetlifediabetes) | [sQ3r1oIsaBY](https://unsplash.com/photos/a-group-of-people-sitting-around-a-table-eating-food-sQ3r1oIsaBY) |
| `soup-bowl` | [Dan DeAlmeida](https://unsplash.com/@ddealmeida) | [4aM_QE-HRLw](https://unsplash.com/photos/a-couple-of-people-holding-a-bowl-of-food-4aM_QE-HRLw) |
| `food-parcels` | [Steward Masweneng](https://unsplash.com/@stewardesign) | [fMcRbRaaZiI](https://unsplash.com/photos/a-group-of-people-standing-around-a-purple-plate-fMcRbRaaZiI) |
| `bible-study` | [Ben White](https://unsplash.com/@benwhitephotography) | [qM18dmqsTqk](https://unsplash.com/photos/man-in-black-crew-neck-t-shirt-holding-black-tablet-computer-qM18dmqsTqk) |
| `bible-coffee` | [Nicolas Lobos](https://unsplash.com/@lobosnico) | [rHwMkuJD6GM](https://unsplash.com/photos/black-smartphone-on-white-notebook-rHwMkuJD6GM) |
| `coffee-friends` | [Vitaly Gariev](https://unsplash.com/@silverkblack) | [_9rMpg5aI8k](https://unsplash.com/photos/people-talking-at-cafe-wooden-table-_9rMpg5aI8k) |
| `coffee-group` | [Vitaly Gariev](https://unsplash.com/@silverkblack) | [BlCgKHTRkFI](https://unsplash.com/photos/friends-chat-and-enjoy-coffee-at-a-cafe-BlCgKHTRkFI) |
| `students-lecture` | [Vitaly Gariev](https://unsplash.com/@silverkblack) | [T9yehHSvLL4](https://unsplash.com/photos/students-talking-in-a-lecture-hall-classroom-T9yehHSvLL4) |
| `students-fair` | [Aayush Khator](https://unsplash.com/@aayushkhator) | [VzeCjrU0V04](https://unsplash.com/photos/a-crowd-of-people-at-an-outdoor-event-VzeCjrU0V04) |
| `students-lawn` | [Dominic Kurniawan Suryaputra](https://unsplash.com/@d_ks11) | [tputvRf4bjA](https://unsplash.com/photos/a-group-of-people-sitting-on-top-of-a-lush-green-field-tputvRf4bjA) |
| `prayer-group` | [Elianna Gill](https://unsplash.com/@elianna_gill03) | [Q588c92mWEI](https://unsplash.com/photos/a-group-of-people-standing-around-each-other-Q588c92mWEI) |
| `visit-tea` | [Centre for Ageing Better](https://unsplash.com/@ageing_better) | [GJaWV0YoBeU](https://unsplash.com/photos/three-seniors-talking-and-smiling-together-GJaWV0YoBeU) |
| `welcome-hug` | [Filip Rankovic Grobgaard](https://unsplash.com/@filipgrobgaard) | [tkI306JXz7o](https://unsplash.com/photos/a-group-of-people-embracing-and-laughing-together-tkI306JXz7o) |
| `welcome-greeting` | [Erika Giraud](https://unsplash.com/@erikasayssmile) | [7KhbREQPFD4](https://unsplash.com/photos/two-men-hugging-on-focus-photography-7KhbREQPFD4) |
| `friends-picnic` | [Vitaly Gariev](https://unsplash.com/@silverkblack) | [ux5wWkiW4ZA](https://unsplash.com/photos/friends-celebrating-a-birthday-outdoors-with-a-cake-ux5wWkiW4ZA) |
| `family-picnic` | [Ainur Iman](https://unsplash.com/@mynameisiknow) | [IVCbWMeiFk4](https://unsplash.com/photos/family-picnic-in-sunlit-park-IVCbWMeiFk4) |
| `family-walk` | [Gray Clary](https://unsplash.com/@grayclary57) | [9eU9t4vxQVk](https://unsplash.com/photos/a-group-of-people-walking-down-a-path-in-a-park-9eU9t4vxQVk) |
| `pastor-thandi` | [K Studios](https://unsplash.com/@kstudios) | [pvwaNk2E-6E](https://unsplash.com/photos/a-smiling-woman-with-braided-hair-and-traditional-attire-pvwaNk2E-6E) |
| `pastor-margaret` | [Age Cymru](https://unsplash.com/@agecymru) | [1Mo0BfBzjBk](https://unsplash.com/photos/a-smiling-woman-stands-before-a-rustic-corrugated-building-1Mo0BfBzjBk) |
| `pastor-peter` | [ben o'bro](https://unsplash.com/@benobro) | [C5XyLljkMrY](https://unsplash.com/photos/man-taking-a-selfie-C5XyLljkMrY) |
| `pastor-naidoo` | [manish_ jadhav_photography05](https://unsplash.com/@mjphotography05) | [6jzu-aBdfUU](https://unsplash.com/photos/woman-and-man-in-traditional-attire-6jzu-aBdfUU) |
| `pastor-moore` | [Alef Morais](https://unsplash.com/@alef_visuals) | [Bop-YufQ-LQ](https://unsplash.com/photos/a-smiling-couple-stands-together-near-the-ocean-Bop-YufQ-LQ) |
| `pastor-andile` | [Idowu Emmanuel](https://unsplash.com/@springimagix) | [1D41F-bt6p0](https://unsplash.com/photos/man-in-blue-and-white-striped-button-up-shirt-smiling-1D41F-bt6p0) |
| `pastor-willem` | [Kyle Bushnell](https://unsplash.com/@kylebushnell) | [ZhAWv5iuFGQ](https://unsplash.com/photos/man-in-black-crew-neck-shirt-ZhAWv5iuFGQ) |
| `pastor-daniel` | [Mina Rad](https://unsplash.com/@miinrad) | [1pLb0DK4_1o](https://unsplash.com/photos/a-man-with-a-beard-sitting-on-some-steps-1pLb0DK4_1o) |
| `pastor-ian` | [Shubham Sharan](https://unsplash.com/@shubhamsharan) | [WCZ_1bx6D5I](https://unsplash.com/photos/a-man-wearing-glasses-WCZ_1bx6D5I) |
| `team-pieter` | [Vicky Hladynets](https://unsplash.com/@vhladynets) | [_gDoyVv5F4c](https://unsplash.com/photos/man-in-white-crew-neck-shirt-_gDoyVv5F4c) |
| `team-lerato` | [Christina @ wocintechchat.com M](https://unsplash.com/@wocintechchat) | [Kpd-JMLeKJk](https://unsplash.com/photos/woman-standing-and-smiling-Kpd-JMLeKJk) |
| `team-johan` | [Lance Reis](https://unsplash.com/@lancereis) | [TTdJV-K1IUg](https://unsplash.com/photos/a-man-with-a-beard-wearing-a-hat-TTdJV-K1IUg) |
| `team-sipho` | [Inocent Drici](https://unsplash.com/@inidrici) | [OGljLs0DnJ4](https://unsplash.com/photos/young-black-man-with-a-big-smile-OGljLs0DnJ4) |
| `team-anne` | [Davide Aracri](https://unsplash.com/@davieees) | [0NDVW4wO1Ms](https://unsplash.com/photos/a-woman-with-dark-hair-0NDVW4wO1Ms) |
| `team-david` | [Christophe Meyer](https://unsplash.com/@christophe_myr) | [2k1RUXZhMPY](https://unsplash.com/photos/man-in-red-crew-neck-shirt-2k1RUXZhMPY) |
| `team-claire` | [PodMatch](https://unsplash.com/@podmatch) | [2mMhaoBGjCs](https://unsplash.com/photos/woman-in-black-blazer-smiling-2mMhaoBGjCs) |
| `team-tom` | [Peri Stojnic](https://unsplash.com/@whoisperi) | [G9dttphDDE4](https://unsplash.com/photos/man-in-black-crew-neck-t-shirt-G9dttphDDE4) |
| `team-nomsa` | [Brian Kungu](https://unsplash.com/@oldceltic) | [olDpu0_Q-A0](https://unsplash.com/photos/a-woman-in-a-denim-shirt-holds-a-cup-olDpu0_Q-A0) |
| `team-kagiso` | [Divine Effiong](https://unsplash.com/@iamdivineeffiong) | [O1lbOY0H5rc](https://unsplash.com/photos/man-in-black-crew-neck-t-shirt-O1lbOY0H5rc) |
| `team-megan` | [Felipe Souza](https://unsplash.com/@dszlipe) | [Vc_mU9UmJbM](https://unsplash.com/photos/woman-in-black-hoodie-and-blue-chair-Vc_mU9UmJbM) |
| `team-ruan` | [Nathan Dumlao](https://unsplash.com/@nate_dumlao) | [26rK1-bH9Ls](https://unsplash.com/photos/man-in-gray-crew-neck-shirt-smiling-26rK1-bH9Ls) |
| `team-ayesha` | [Mehrpouya H](https://unsplash.com/@mehrpouya) | [isuiNDHQPzs](https://unsplash.com/photos/woman-in-white-t-shirt-outdoors-isuiNDHQPzs) |
| `team-chris` | [Joseph Gonzalez](https://unsplash.com/@miracletwentyone) | [iFgRcqHznqg](https://unsplash.com/photos/man-wearing-white-v-neck-shirt-iFgRcqHznqg) |
| `team-grace` | [NORBAINE GLORY TAMAR](https://unsplash.com/@g_light) | [o9LPROnZJfA](https://unsplash.com/photos/woman-in-red-blazer-o9LPROnZJfA) |
| `team-michelle` | [Troy Spoelma](https://unsplash.com/@spoelee4) | [EV8PPQG6zxY](https://unsplash.com/photos/a-woman-with-long-hair-wearing-a-blue-blazer-EV8PPQG6zxY) |
| `team-reddy` | [Pranit Tandon](https://unsplash.com/@prantan) | [BJ_PVL5vpc4](https://unsplash.com/photos/man-and-woman-embracing-in-park-BJ_PVL5vpc4) |
| `team-lwazi` | [150 Billi](https://unsplash.com/@150billi) | [dRgM67tRZHk](https://unsplash.com/photos/a-man-with-a-beard-and-a-green-shirt-dRgM67tRZHk) |
| `team-elsie` | [Hosein Sediqi](https://unsplash.com/@hoseinsediqii) | [sBkSyfPzakI](https://unsplash.com/photos/an-older-woman-with-white-hair-and-a-smile-sBkSyfPzakI) |
| `team-bongani` | [melvin Ankrah](https://unsplash.com/@hashtagmelvin) | [fEY925P2GlQ](https://unsplash.com/photos/a-happy-black-man-smiling-in-a-black-shirt-fEY925P2GlQ) |
| `team-marie` | [Doug Bagg](https://unsplash.com/@dougbagg_) | [9iLbXsMZ6ls](https://unsplash.com/photos/smiling-woman-in-brown-blazer-9iLbXsMZ6ls) |
| `team-refilwe` | [alex starnes](https://unsplash.com/@alexstarnes) | [PK_t0Lrh7MM](https://unsplash.com/photos/smiling-woman-in-yellow-blazer-holding-tablet-PK_t0Lrh7MM) |
| `team-sam` | [Its me Pravin](https://unsplash.com/@paul__pro) | [duzGG1gkgMw](https://unsplash.com/photos/a-man-leaning-over-a-wooden-table-in-a-warehouse-duzGG1gkgMw) |
| `team-nadia` | [amin naderloei](https://unsplash.com/@aminnaderloei) | [OmjeNvHwkDI](https://unsplash.com/photos/a-smiling-woman-sits-outdoors-on-a-rock-OmjeNvHwkDI) |
| `team-lisa` | [Ionela Mat](https://unsplash.com/@ionelaaaaa) | [s3PJLnFKjnI](https://unsplash.com/photos/woman-smiles-while-posing-near-foliage-s3PJLnFKjnI) |
| `team-thabo` | [nana o.](https://unsplash.com/@afroscope) | [10fvuGtnoEM](https://unsplash.com/photos/man-near-tree-10fvuGtnoEM) |
| `team-priya` | [amin naderloei](https://unsplash.com/@aminnaderloei) | [5KsbzX5M9mo](https://unsplash.com/photos/young-woman-in-glasses-smiling-in-a-forest-5KsbzX5M9mo) |
| `open-bible` | [Sixteen Miles Out](https://unsplash.com/@sixteenmilesout) | [L-mNqn89I2s](https://unsplash.com/photos/green-plant-on-white-book-page-L-mNqn89I2s) |
| `pulpit` | [Mitchell Leach](https://unsplash.com/@mitchellleach) | [DmdQGZqR_38](https://unsplash.com/photos/brown-wooden-cross-on-brown-wooden-cabinet-DmdQGZqR_38) |
| `church-quiet` | [Martin Jernberg](https://unsplash.com/@martinjernberg) | [ySjfkwugiEA](https://unsplash.com/photos/a-man-sitting-in-a-church-with-stained-glass-windows-ySjfkwugiEA) |
| `sermon-robe` | [Benjamin Brunner](https://unsplash.com/@ben_brunner) | [MbYFGJT06gk](https://unsplash.com/photos/a-man-in-a-black-robe-holding-a-book-MbYFGJT06gk) |
| `sermon-collar` | [RECARDO DAVIDSON](https://unsplash.com/@shotbyriki) | [26JmMEHe9nk](https://unsplash.com/photos/clergywoman-in-black-suit-stands-before-a-stone-wall-26JmMEHe9nk) |
| `sermon-stage` | [Phil Hearing](https://unsplash.com/@philhearing) | [mgPIJGLM0SU](https://unsplash.com/photos/a-man-standing-on-top-of-a-stage-next-to-a-microphone-mgPIJGLM0SU) |
| `sermon-hall` | [adrianna geo](https://unsplash.com/@adrigeo_) | [xjzhVNOvfZM](https://unsplash.com/photos/people-sitting-on-chairs-inside-room-xjzhVNOvfZM) |
| `sermon-dark` | [Zach Lucero](https://unsplash.com/@zlucerophoto) | [X4V-El4qvZ4](https://unsplash.com/photos/a-man-in-a-suit-and-tie-holding-a-piece-of-paper-X4V-El4qvZ4) |
| `mic-audience` | [Joao Cruz](https://unsplash.com/@jcruzweb) | [IkEpl3JkVqU](https://unsplash.com/photos/shallow-focus-photo-of-black-corded-microphone-IkEpl3JkVqU) |
| `mic-blue` | [Matthias Wagner](https://unsplash.com/@matwag) | [QrqeusbpFMM](https://unsplash.com/photos/black-and-gray-microphone-on-black-stand-QrqeusbpFMM) |
| `mic-red` | [Allie Reefer](https://unsplash.com/@thepghtraveler) | [rAoQn6kwv64](https://unsplash.com/photos/a-microphone-on-a-stand-in-front-of-a-red-background-rAoQn6kwv64) |
| `mic-white` | [Madrosah Sunnah](https://unsplash.com/@26_ms) | [UA1nd6-Dndw](https://unsplash.com/photos/black-and-gray-microphone-on-white-background-UA1nd6-Dndw) |
| `mic-crowd` | [Herlambang Tinasih Gusti](https://unsplash.com/@tinasihgusti) | [-ymBs1mVim8](https://unsplash.com/photos/a-man-standing-in-front-of-a-crowd-of-people--ymBs1mVim8) |
Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 243 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 275 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

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