Compare commits

...
Author SHA1 Message Date
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
joshua 35501deb0d Merge branch 'fix/website-starter-pages' 2026-11-27 08:18:53 +02:00
joshuaandClaude Opus 5.5 79e1450df6 Website 1.2.0: starter pages on a new install, and a site icon
A new install had no pages, so the home page and its live preview showed
only the header and footer (found on cross-demo2). The backend now adds the
fixed pages with starter text at startup. Settings -> Site icon sets the
favicon, with a default from the church's colour and initial. The Latest
message's Card layout has its name; the media picker's placeholder has
enough contrast.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 09:17:32 +02:00
joshua e04bfac208 Merge branch 'docs/deployed-frp-release' 2026-11-21 11:13:40 +02:00
joshuaandClaude Opus 5.5 7677f54056 docs: agent 1.4.0 and Hub 2.11.0 deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:13:39 +02:00
484 changed files with 31251 additions and 456 deletions
+275
View File
@@ -2,6 +2,281 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## 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
CHANGELOG.md. No migrations, no backend changes.
- **Accounts 1.8.0:** `/admin` is an overview (cards, "Needs you", a tile per section); People
moved to `/admin/people`; the sidebar shows the part you're in, grouped; People redesigned.
- **Website 1.1.0:** an icon sidebar in groups, a dashboard, steps to the first publish across the
top, and a live preview beside the page editor and Template and style (drafts in a frame, no
preview cookie).
## accounts@1.7.1 + website@1.0.2 + events@3.7.1 - 2026-11-26
Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations.
- **Linking right after an install** (all three): a connect involving an install that isn't in the
cached copy of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at most once a
minute) instead of refusing. Before, a new product and its siblings only learned of each other at
their 15-minute heartbeats, so a new Website's admin couldn't sign in for up to 30 minutes.
- **Accounts 1.7.1:** also a heartbeat on every start.
- **Website 1.0.2:** opening `/admin` without a link to Accounts links on the spot; the problem page
says "not linked yet" (`ACCOUNTS_NOT_LINKED`) instead of "can't reach your sign-in". Preview no
longer redirects to the server's own `http://localhost:<web port>` (relative redirects).
- **Events 3.7.1:** a new Website can connect for the event feed straight away.
## website@1.0.1 + crosscode script - 2026-11-26
Details in `apps/website/CHANGELOG.md`.
- **Website 1.0.1:** the messages' YouTube thumbnails are served from the site
(`/api/thumbnails/<id>.jpg`), so visitors ask nothing of YouTube until they press play; the
Calendar events' dates read "Sun · November", not "Sun (month: November)". No migration.
- **crosscode script:** a Website's export leaves out `uploads/.thumbnails` (the kept thumbnails).
## contracts@1.18.0 - 2026-11-25
"Get more storage" for the Church Website (WEBSITE-1.0-PLAN §10, decision 12), with Hub 2.22.0.
Additive: products on 1.17.0 keep working.
- **`hub.storageRequestSchema` / `storageRequestResponseSchema`**: a Website asks the Hub for more
5 GB steps (`POST /api/installs/storage-request`, signed as the heartbeat), with what it uses,
its limit and who asked. `hub.STORAGE_STEP_BYTES`. New sample `hub-storage-request.json` and
JSON Schemas `hub-storage-request`, `hub-storage-request-response`.
## events@3.7.0 + @crosscode/ui 0.3.0 - 2026-11-24
Cross Events' public pages use the church's brand style and the shared footer (WEBSITE-1.0-PLAN §9).
Details in `apps/events/CHANGELOG.md`.
- **Events 3.7.0:** the church profile from Accounts (`GET /api/v2/church`), its fonts and corners
on the public pages, `ChurchFooter` and links to the church's other sites; `church.changed` is
accepted at `/api/church/v1/changed`. Dashboard and setup unchanged. No migrations.
- **`@crosscode/ui` 0.3.0:** `ChurchFooter` takes `bottom` (a product's own links).
## contracts@1.17.0 + accounts@1.7.0 + @crosscode/ui 0.2.0 - 2026-11-24
The first release of the Church Website 1.0.0 work (WEBSITE-1.0-PLAN §12). The contracts are
additive and optional: products on 1.16.0 keep working. Accounts 1.7.0 ships with them because it
answers the new `church.update` request. Details of Accounts in `apps/accounts/CHANGELOG.md`.
- **Brand style** (`./style`): the 8 font pairings confirmed on 2026-11-24 (`FONT_PAIRINGS`:
`classic`, `scholarly`, `editorial`, `impact`, `contemporary`, `friendly`, `warm`, `modern`, each
with its heading and body font), the corner styles (`CORNERS`, `DEFAULT_CORNERS` = `soft`), the
Website's templates (`WEBSITE_TEMPLATES`) and the three pairings each recommends
(`TEMPLATE_FONT_PAIRINGS`, default first). The ids are stored in profiles and never change.
- **`crosscode.church/1`:** optional `branding.style` (`fontPairing`, `corners`, each nullable). An
id a product doesn't know yet reads as null, so a newer Accounts never breaks an older product.
- **`crosscode.church-export/1`:** an optional `website` part (template, first publish, style
settings, pages with their sections, messages, simple events, the publish history's notes and
the media library's alt text). New sample `church-export-website.json`.
- **`church.update`** (identity request, product → Accounts, signed with the link's secret): the
Website's admin changes shared profile facts (plan decision 10). The product checks the person's
role and sends them as `actor`; only the fields given change (`branding` field by field); live at
once, then `church.changed`. Optional `ifUpdatedAt` refuses with the new error code
`PROFILE_CHANGED` when someone saved in between. Reply: the profile (`churchUpdateReplySchema`).
Accounts 1.7.0 takes it from the Website only.
- **Licence:** optional `limits.storageBytes`, the Website's storage limit including add-ons (plan
decision 12). New sample `hub-licence-payload-website.json`.
- **Accounts 1.7.0:** the brand style in Admin → Church profile, the church's fonts, corners and
shared footer on its pages, and `church.update` from the Website. Update Accounts before (or with)
anything that sends `church.update`; nothing does until the Website.
- **`@crosscode/ui` 0.2.0:** `fonts.css` (the 8 pairings' fonts, Latin and Latin Extended, from the
pinned `@fontsource-variable` packages, with Capsize size-matched fallbacks on Arial or Georgia;
generated by `scripts/fonts.mjs`, checked by `npm test`, at most 160 KB per pairing for an
English page), `brandAttributes`, `ChurchFooter`, `productLinks`; the components' corners follow
`--cc-radius` and headings the pairing's heading font. Apps without a pairing look as before.
- `package-lock.json` catches up with the agent's and contracts' versions.
## agent@1.5.0 + contracts@1.16.0 + crosscode script - 2026-11-23
- **Fix: uninstalling one product removed the whole church.** `crosscode uninstall <church>` only
knew whole churches, while the Hub uninstalls per product: uninstalling cross-events-demo's
Events also removed its Accounts, which the Hub still showed as live, and its own uninstall
failed later ("No church cross-events-demo on this server").
- **`crosscode uninstall|export|purge <church> [product …]`.** With products named, only those
are backed up, kept (`.removed/<church>-<date>/<product>`) and removed; the church keeps the
others in church.env. Naming every product it still has removes the church (folder and app
user), so the last product to go always takes the church with it. The report gives `products`
and `remaining`. `purge` with products deletes only what was kept of those, also while the
church still has others. Without products, as before.
- **Agent 1.5.0** passes `products` through. **Contracts 1.16.0:** optional `products` on the
`export`, `uninstall` and `purge` job arguments, and `PRODUCT_UNINSTALL_MIN_AGENT` (an older
agent refuses the key). Hub 2.12.0 uses them.
- The Church Website plan's versions move up one again: contracts 1.17.0, Hub 2.13.0.
## agent@1.4.0 + contracts@1.15.0 - 2026-11-21
- **Agent 1.4.0: frp's config, wherever it is.** The agent no longer assumes
+113
View File
@@ -1,5 +1,118 @@
# Changelog — Accounts
## [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
dashboard and settings.
### Changed
- **`/admin` is an overview:** four cards (people with an account, deletion requests waiting,
sites that sign in here, last backup), a "Needs you" list with buttons to act, and a tile with a
line about every section. **People moved to `/admin/people`.**
- **The sidebar shows the part you're in** (your account or admin, with a link to the other), and
admin's sections are grouped: People, Church, Signing in, System. Deletion requests shows how many
are waiting. The phone menu shows both parts. Every page title has its section's icon.
- **People:** a search box, a row per person with initials, admin and status badges, two-step
sign-in and last sign-in; the person's card stays in view while scrolling. Deactivating someone
asks to confirm first.
- **Email and WhatsApp** are two cards, each with its own Save.
- Group labels are a darker grey (WCAG AA contrast).
## [1.7.1] - 2026-11-26
No migrations, no new settings.
### Fixed
- **A product installed after Accounts' last heartbeat links straight away.** Accounts accepted a
connect only from installs in its cached copy of the Hub's list, which it refreshed every 15
minutes. A new Church Website (or Events) was refused ("doesn't know that install yet") and tried
again only at its own next heartbeat, so its admin couldn't sign in for up to 30 minutes after the
install (found on cross-demo2). Now, for an install it doesn't know, Accounts sends the Hub a
heartbeat to get a fresh list and looks again (at most one such heartbeat a minute, so unknown
installs can't make it call the Hub more often). The same applies when an Accounts admin connects.
- **A heartbeat on every start**, not only the first: after a restart the list of the church's
products is fresh at once.
## [1.7.0] - 2026-11-24
Needs contracts 1.17.0. The first part of the Church Website 1.0.0 (WEBSITE-1.0-PLAN §11).
### Added
- **Brand style** in the church profile (`branding.style`: font pairing and corners, contracts
1.17.0). Admin → Church profile → **Brand style** shows each of the 8 pairings in its own fonts,
and the three corner styles. Served in `GET /api/church/v1` and `/api/v2/branding`.
- **The church's fonts and corners on Accounts' pages**: `@crosscode/ui/fonts.css` (self-hosted, no
font requests to anyone else) and `brandAttributes` on `<html>`. Without a pairing the pages
keep the device fonts, so nothing changes until an admin picks one.
- **The shared footer** (`ChurchFooter` from `@crosscode/ui`) on the public pages (sign in, forgot
and reset password, signed out, confirm email): service times, address, contact, social links,
links to the church's other sites and the privacy notice, from the church profile.
- **`church.update`** (contracts 1.17.0): the church's Website changes shared profile facts for its
admins (WEBSITE-1.0-PLAN decision 10). Only from a product linked as `website`
(`WRONG_PRODUCT`), only for an `actor` who signs in through it (`NOT_ALLOWED`), and refused
with `PROFILE_CHANGED` (409) when `ifUpdatedAt` is out of date. Live at once; linked products get
`church.changed`; audited as `church_profile_changed_by_product` with the fields changed.
### Changed
- Saving the profile merges `branding` field by field (`mergeProfile`), so a form or product that
sends only part of it (the colours without the style, or only the style) never drops the rest.
## [1.6.0] - 2026-11-20
### Added
+34
View File
@@ -3,6 +3,40 @@
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
- **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
needs you (like deletion requests waiting), and a tile for every setting. The menu down the side
is grouped and shows only the part you're in. People has moved to Admin → **People**, with a
search box and a clearer list; deactivating someone now asks you to confirm.
## 1.7.1
- **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed
for your church can be signed in to within moments, instead of after up to half an hour.
## 1.7.0
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
pairings, each shown in its own fonts, and sharp, soft or round corners. Your sign-in pages use
them now, and your new Church Website and Cross Events' public pages will too, so all your sites
look like one church. Until you pick, nothing changes.
- **A footer with your church's details** under the sign-in pages: service times, address, contact
details and links to your church's other sites, from the church profile.
- Getting ready for the **Church Website**: its admins will be able to change your service times,
logo and contact details from the website, and they'll change everywhere at once.
## 1.6.0
- **You're told about each sign-in.** After someone signs in, they get an email saying when, roughly
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.6.0",
"version": "1.9.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' }));
+31 -3
View File
@@ -69,10 +69,37 @@ export class ProfileError extends Error {
}
}
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
/** The profile changed since the editor loaded it (`church.update` with `ifUpdatedAt`). */
export class ProfileChangedError extends Error {
constructor(public updatedAt: string) {
super('The church profile was changed by someone else since you opened it.');
}
}
const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
/**
* The fields given replace what's there; `branding` is merged field by field (1.7.0), so a form
* that doesn't know `branding.style` (or sends only the style) never drops the rest.
*/
export function mergeProfile(base: Record<string, unknown>, input: unknown): Record<string, unknown> {
if (!isObject(input)) return { ...base };
const next: Record<string, unknown> = { ...base, ...input };
if (isObject(input.branding)) next.branding = { ...(isObject(base.branding) ? base.branding : {}), ...input.branding };
return next;
}
/**
* Saves changes (merged onto what's there) from an admin here or a product (`church.update`),
* and tells the linked products. With `ifUpdatedAt`, refuses if someone saved since.
*/
export async function updateProfile(ctx: Ctx, input: unknown, opts: { ifUpdatedAt?: string } = {}): Promise<Church> {
const current = await storedProfile(ctx);
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
if (opts.ifUpdatedAt) {
const now = current.updatedAt ?? new Date(0).toISOString();
if (new Date(now).getTime() !== new Date(opts.ifUpdatedAt).getTime()) throw new ProfileChangedError(now);
}
const next = mergeProfile({ ...DEFAULTS(ctx), ...current }, input);
const check = profileInputSchema.safeParse(next);
if (!check.success) {
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
@@ -92,6 +119,7 @@ export async function branding(ctx: Ctx) {
shortName: c.shortName,
logoUrl: c.branding.logoUrl,
colours: c.branding.colours,
style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: c.branding.style?.corners ?? null },
signupEnabled: await ctx.settings.bool('signup_enabled', true),
};
}
@@ -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 };
}
+3 -1
View File
@@ -23,8 +23,10 @@ async function main() {
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
const stopJobs = await startJobs(ctx, url);
// 1.7.1: a heartbeat on every start, not only the first (as the Website), so the list of the
// church's products is fresh after a restart.
connectFromEnv(ctx).then((r) => {
if (r.connected) heartbeat(ctx).catch(() => {});
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
@@ -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([
+28 -4
View File
@@ -11,6 +11,7 @@ import {
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { heartbeat } from '../hub/client.js';
import { audit, clientIp } from '../lib/audit.js';
import { callSibling, LinkCallError, siblingUrl } from './http.js';
import { keyPair, listedProduct } from './store.js';
@@ -24,6 +25,29 @@ export class LinkError extends Error {
/** Products that sign people in through Accounts. */
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after Accounts' last heartbeat), Accounts asks the Hub for a fresh list with a heartbeat and looks
* again, so a new Website links straight away instead of up to 30 minutes later. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make Accounts call the Hub
* more often than that.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
r = { at: now, run: heartbeat(ctx).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
return listedProduct(ctx, installId);
}
async function self(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
@@ -55,8 +79,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
const sibling = await listedProduct(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -86,9 +110,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(ctx, m.from.installId);
const sibling = await listedOrRefreshed(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (Accounts asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
@@ -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 });
}
+66 -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';
@@ -31,6 +31,12 @@ import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent
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']);
/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */
export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
@@ -130,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 };
}
@@ -221,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;
@@ -255,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 });
@@ -319,6 +327,36 @@ 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.
if (!PROFILE_EDITORS.has(link.product)) throw new RequestError("Only the church's Website changes the church profile from outside Accounts.", 'WRONG_PRODUCT', 403);
const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: r.actor } });
if (!known) throw new RequestError("The person making the change isn't someone who signs in to this product.", 'NOT_ALLOWED', 403);
try {
const church = await updateProfile(ctx, r.church, { ifUpdatedAt: r.ifUpdatedAt });
await logRequest(ctx, link, r, 'church_profile_changed_by_product', null, req, { fields: Object.keys(r.church) });
return reply({ church });
} catch (e) {
if (e instanceof ProfileChangedError) throw new RequestError(e.message, 'PROFILE_CHANGED', 409);
if (e instanceof ProfileError) throw new RequestError(`${e.message} ${Object.entries(e.fields).map(([k, v]) => `${k}: ${v}`).join('; ')}`.trim(), 'INVALID_REQUEST', 400);
throw e;
}
}
case 'church.branding': {
const changed = await applyLook(ctx, r.church, r.overwrite);
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
@@ -362,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 } });
@@ -399,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(() => {});
}
@@ -445,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,108 @@
// church.update (contracts 1.17.0, Accounts 1.7.0, WEBSITE-1.0-PLAN decision 10): the Website's
// admin changes shared profile facts through Accounts, and the brand style is kept by every save.
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { after, before, describe, test } from 'node:test';
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, signedHeaders } from '@crosscode/contracts/signing';
import { startHarness, type Harness } from './support/harness.js';
import { church, mergeProfile, updateProfile } from '../src/church/profile.js';
const WEBSITE_ID = '7e2a1c3d-9b4f-4d6e-8f70-2b3c4d5e6f70';
const EVENTS_ID = '8f3b2d4e-0c5a-4e7f-9a81-3c4d5e6f7a81';
let h: Harness;
const secrets: Record<string, string> = {};
let editor: string;
before(async () => {
h = await startHarness();
for (const [id, product] of [[WEBSITE_ID, 'website'], [EVENTS_ID, 'events']] as const) {
secrets[id] = newLinkSecret();
await h.db.productLink.create({
data: { installId: id, product, url: `https://${product}.hope.test`, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secrets[id]!), connectedAt: new Date() },
});
}
const a = await h.makeAccount({ email: 'editor@hope.test' });
editor = a.id as string;
for (const linkId of [WEBSITE_ID, EVENTS_ID]) await h.db.productPerson.create({ data: { linkId, accountId: editor, via: 'sign_in', createdAt: new Date() } });
await updateProfile(h.ctx, { name: 'Hope Family Church', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } } });
});
after(async () => { await h.close(); });
async function ask(body: Record<string, unknown>, from = WEBSITE_ID) {
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: editor, type: 'church.update', ...body });
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret: secrets[from]!, rawBody: raw });
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
}
describe('church.update from the Website', () => {
test('changes only the style, keeps the colours and logo, and goes live at once', async () => {
const res = await ask({ church: { branding: { style: { fontPairing: 'warm', corners: 'round' } } } });
assert.equal(res.status, 200, JSON.stringify(res.body));
const c = await church(h.ctx);
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'round' });
assert.equal(c.branding.colours.primary, '#1f4e79');
assert.equal(c.name, 'Hope Family Church');
assert.deepEqual((res.body.church as { branding: unknown }).branding, c.branding);
});
test('tells every linked product the profile changed, and audits it as the editor', async () => {
const before = await h.db.delivery.count();
const res = await ask({ church: { shortName: 'Hope Family' } });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.ok((await h.db.delivery.count()) > before);
const log = await h.db.auditLog.findFirst({ where: { action: 'church_profile_changed_by_product' }, orderBy: { createdAt: 'desc' } });
assert.equal(log?.actorId, editor);
});
test('refuses another product, someone who doesn\'t sign in through the Website, and a stale edit', async () => {
const events = await ask({ church: { name: 'Hijacked' } }, EVENTS_ID);
assert.equal(events.status, 403);
assert.equal(events.body.code, 'WRONG_PRODUCT');
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
const notKnown = await ask({ actor: stranger.id as string, church: { name: 'Hijacked' } });
assert.equal(notKnown.status, 403);
assert.equal(notKnown.body.code, 'NOT_ALLOWED');
const stale = await ask({ ifUpdatedAt: '2020-01-01T00:00:00.000Z', church: { name: 'Hijacked' } });
assert.equal(stale.status, 409);
assert.equal(stale.body.code, 'PROFILE_CHANGED');
assert.equal((await church(h.ctx)).name, 'Hope Family Church');
});
test('takes an edit made on the current version', async () => {
const current = await church(h.ctx);
const res = await ask({ ifUpdatedAt: current.updatedAt, church: { serviceTimes: [{ day: 'sunday', time: '09:00', label: null, campus: null, note: null }] } });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal((await church(h.ctx)).serviceTimes.length, 1);
});
test('an invalid value is refused with what\'s wrong', async () => {
const res = await ask({ church: { contact: { email: null, phone: '016 123', whatsapp: null, address: null } } });
assert.equal(res.status, 400);
assert.equal(res.body.code, 'INVALID_REQUEST');
});
});
describe('saving the profile keeps the brand style', () => {
test('an admin form that sends branding without the style doesn\'t drop it', async () => {
await updateProfile(h.ctx, { branding: { style: { fontPairing: 'classic', corners: 'sharp' } } });
await updateProfile(h.ctx, { branding: { logoUrl: null, iconUrl: null, colours: { primary: '#204060', accent: null } } });
const c = await church(h.ctx);
assert.deepEqual(c.branding.style, { fontPairing: 'classic', corners: 'sharp' });
assert.equal(c.branding.colours.primary, '#204060');
});
test('mergeProfile replaces other fields whole and merges branding', () => {
const merged = mergeProfile({ name: 'A', social: [1], branding: { logoUrl: 'x', colours: { primary: '#000000' } } }, { social: [], branding: { colours: { primary: '#ffffff' } } });
assert.deepEqual(merged, { name: 'A', social: [], branding: { logoUrl: 'x', colours: { primary: '#ffffff' } } });
});
test('the sign-in pages get the style', async () => {
const res = await fetch(`${h.publicUrl}/api/v2/branding`);
const b = (await res.json()) as { style: unknown };
assert.deepEqual(b.style, { fontPairing: 'classic', corners: 'sharp' });
});
});
@@ -0,0 +1,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);
});
});
@@ -2,6 +2,8 @@
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
// church profile, Connect, and admin and setup rules.
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { after, before, beforeEach, describe, test } from 'node:test';
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
@@ -156,6 +158,44 @@ describe('Connect from a product', () => {
const client = await h.provider.Client.find(APP_ID);
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
});
test('1.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const own = await startHarness({ now: () => clock });
const appKey = generateEd25519();
const NEW_ID = '5c1d7e2f-8a3b-4c4d-9e5f-6a7b8c9d0e1f';
const listed = { product: 'website', installId: NEW_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) };
// A Hub whose list has the new Website; Accounts' cached list doesn't yet.
const hubCalls: string[] = [];
const hub = http.createServer((req, res) => {
hubCalls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: [listed] }));
});
await new Promise<void>((r) => hub.listen(0, '127.0.0.1', () => r()));
try {
own.ctx.config.hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
await own.ctx.settings.setMany({ hub_install_secret: 'secret', hub_linked_products: '[]' });
const msg = (installId: string) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'website', installId, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: clock.toISOString(), nonce: newLinkNonce() }, appKey.privateKeyPem);
const send = (installId: string) => fetch(`${own.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(installId)) });
assert.equal((await send(NEW_ID)).status, 200, 'linked at once');
assert.deepEqual(hubCalls, ['/api/installs/heartbeat']);
assert.equal(await own.db.productLink.count({ where: { installId: NEW_ID } }), 1);
// An install the Hub doesn't list: refused, and within the minute the Hub isn't asked again.
const UNKNOWN = '7e3f9a4b-0c5d-4e6f-8a7b-9c0d1e2f3a4b';
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 1);
clock = new Date(clock.getTime() + 61_000);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 2);
} finally {
await new Promise((r) => hub.close(r));
await own.close();
}
});
});
describe('admin and setup', () => {
@@ -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);
});
});
+43
View File
@@ -0,0 +1,43 @@
import AxeBuilder from "@axe-core/playwright";
import { expect, test } from "@playwright/test";
// 1.7.0 (WEBSITE-1.0-PLAN §3, §9): the church's brand style and shared footer on Accounts' public
// pages. The e2e church (e2e/server.ts) has the "warm" pairing, round corners and service times.
const PRODUCT = "http://localhost:5211";
test("the sign-in page uses the church's fonts and corners, and shows its footer", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm");
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
const heading = page.getByRole("heading", { name: "Sign in to Hope Family Church" });
expect(await heading.evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Fraunces");
expect(await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Nunito Sans");
// The font files themselves load from this site (self-hosted), not from anyone else.
await page.evaluate(() => document.fonts.ready);
expect(await page.evaluate(() => document.fonts.check('600 20px "CC Fraunces"'))).toBe(true);
expect(await page.getByRole("button", { name: "Sign in" }).evaluate((el) => getComputedStyle(el).borderRadius)).toBe("9999px");
const footer = page.locator("footer");
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
await expect(footer).toContainText("Sundays 09:00");
await expect(footer.getByRole("link", { name: "office@hope.test" })).toHaveAttribute("href", "mailto:office@hope.test");
await expect(footer.getByRole("link", { name: "Website" })).toHaveAttribute("href", PRODUCT);
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/privacy");
});
test("fonts never come from another site", async ({ page }) => {
const foreign: string[] = [];
page.on("request", (r) => { if (/\.(woff2?|ttf|otf)(\?|$)/.test(r.url()) && !r.url().startsWith("http://localhost:3210/")) foreign.push(r.url()); });
await page.goto(`${PRODUCT}/start?returnTo=/`);
await page.evaluate(() => document.fonts.ready);
expect(foreign).toEqual([]);
});
test("the sign-in page with the footer passes axe (WCAG 2.2 AA)", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await expect(page.locator("footer")).toBeVisible();
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
});
+7 -1
View File
@@ -29,7 +29,13 @@ const messenger = new MemoryMessenger();
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
await ctx.settings.setMany({
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
// 1.7.0: a brand style, service times and contact details, so the pages show the church's fonts and footer.
church_profile: JSON.stringify({
name: 'Hope Family Church', shortName: 'Hope',
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' }, style: { fontPairing: 'warm', corners: 'round' } },
serviceTimes: [{ day: 'sunday', time: '09:00', label: 'Morning service', campus: null, note: null }],
contact: { email: 'office@hope.test', phone: '+27161234567', whatsapp: null, address: null },
}),
});
const linkSecret = newLinkSecret();
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
+4
View File
@@ -102,6 +102,10 @@ test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click();
await page.getByRole("button", { name: "I've saved them" }).click();
// 1.8.0: /admin is the overview, with a tile for every section; People is one.
await expect(page.getByRole("heading", { name: "Admin", level: 1 })).toBeVisible();
await expect(page.getByText("People with an account")).toBeVisible();
await page.getByRole("navigation", { name: "Admin" }).getByRole("link", { name: "People", exact: true }).click();
await expect(page.getByRole("heading", { name: "People", level: 1 })).toBeVisible();
await expect(page.getByText("thandi@hope.test")).toBeVisible();
// 1.3.0: every admin section has its own address, down the side; Backups is one.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.6.0",
"version": "1.9.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
@@ -6,7 +6,7 @@ import QRCode from "qrcode";
import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { ACCOUNT_NAV, AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -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" }) : "—");
@@ -62,7 +64,7 @@ export function Account({ section = "overview" }: { section?: AccountSection })
const first = me.name.split(" ")[0] || me.name;
return (
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
<PageTitle icon={section === "overview" ? undefined : ACCOUNT_NAV.find((n) => n.href === s.path)?.icon} sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview me={me} />}
{section === "details" && <div className="max-w-2xl"><Profile me={me} onDone={done} onFail={fail} /></div>}
@@ -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">
@@ -2,7 +2,8 @@
import Link from "next/link";
import { useState } from "react";
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
import { Card, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -20,12 +21,12 @@ export function ConfirmEmail({ token }: { token: string }) {
return () => { alive = false; };
}, [token]);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading>Your email address</Heading>
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
<Link href="/account" className="text-brand underline">Back to your account</Link>
</Card>
</Shell>
</PublicShell>
);
}
+206 -35
View File
@@ -2,14 +2,18 @@
import Link from "next/link";
import React, { useCallback, useState } from "react";
import { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react";
import {
AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play,
RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users,
} from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
import { NoticeText } from "@/components/NoticeText";
import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections";
import { BrandStyle } from "./BrandStyle";
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
@@ -25,6 +29,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
const [me, setMe] = useState<ShellUser | null>(null);
const [allowed, setAllowed] = useState<boolean | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const [waiting, setWaiting] = useState(0);
useExternalEffect(() => {
let alive = true;
@@ -34,11 +39,15 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa"));
if (who.ok) setMe(who.data);
setAllowed(r.ok);
// The count beside Deletion requests.
if (r.ok) void call<{ items: Deletion[] }>("GET", "/admin/deletions").then((d) => { if (alive && d.ok) setWaiting(d.data.items.filter((x) => x.status === "waiting_approval").length); });
});
return () => { alive = false; };
}, [s.path]);
const flash: Flash = (tone, text) => setMsg({ tone, text });
const icon = ADMIN_NAV.find((n) => n.href === s.path)?.icon;
const badges = { "/admin/deletions": waiting };
if (allowed === null || !me) return <ShellLoading />;
if (!allowed) {
return (
@@ -49,16 +58,21 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
}
return (
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub}>{s.title}</PageTitle>
<AppShell me={me} active={s.path} badges={badges}>
<PageTitle icon={section === "overview" ? undefined : icon} sub={section === "overview" ? `Welcome back, ${me.name.split(" ")[0] || me.name}. ${s.sub}` : s.sub}>{s.title}</PageTitle>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{section === "overview" && <Overview />}
{section === "people" && <People flash={flash} />}
<div className="max-w-3xl">
{section === "deletions" && <Deletions flash={flash} />}
{section === "church" && <Church flash={flash} />}
<div className="max-w-3xl space-y-6">
{section === "deletions" && <Deletions flash={flash} onChange={setWaiting} />}
{section === "church" && <><Church flash={flash} /><BrandStyle flash={flash} /></>}
{section === "linked" && <Linked flash={flash} />}
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{section === "signin" && <Settings flash={flash} title="Signing in" icon={<LogIn className="h-4 w-4" />} sub="For everyone with an account at the church." keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
{section === "messages" && <>
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
<WhatsAppReplies />
</>}
{section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />}
{section === "jobs" && <Jobs flash={flash} />}
@@ -69,11 +83,118 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
);
}
// ─── Overview (1.8.0, as Cross Events' admin dashboard) ─────────────────────
type Linked = { hubConnected: boolean; items: { installId: string; name: string; listed: boolean; signsInHere: boolean }[] };
type OverviewData = { people: number | null; deletions: number | null; linked: Linked | null; licence: { connected: boolean; state: string } | null; backups: BackupList | null };
const TILE: Record<string, string> = Object.fromEntries(Object.values(ADMIN_SECTIONS).map((x) => [x.path, x.tile]));
function Stat({ icon, label, value, detail, href, warn }: { icon: React.ReactNode; label: string; value: React.ReactNode; detail?: React.ReactNode; href: string; warn?: boolean }) {
return (
<Link href={href} className="group rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<div className="flex items-center gap-3">
<span className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${warn ? "bg-amber-50 text-amber-700" : "bg-brand/10 text-brand"}`} aria-hidden>{icon}</span>
<span className="min-w-0">
<span className="block text-xs text-gray-500">{label}</span>
<span className="block truncate text-xl font-semibold text-gray-900">{value}</span>
</span>
</div>
{detail && <p className="mt-2 text-xs text-gray-500">{detail}</p>}
</Link>
);
}
function Overview() {
const [d, setD] = useState<OverviewData | null>(null);
useExternalEffect(() => {
let alive = true;
Promise.all([
call<{ total: number }>("GET", "/admin/people?q="), call<{ items: Deletion[] }>("GET", "/admin/deletions"), call<Linked>("GET", "/admin/linked-products"),
call<{ connected: boolean; state: string }>("GET", "/admin/licence"), call<BackupList>("GET", "/admin/backups"),
]).then(([people, dels, linked, licence, backups]) => {
if (!alive) return;
setD({
people: people.ok ? people.data.total : null,
deletions: dels.ok ? dels.data.items.filter((x) => x.status === "waiting_approval").length : null,
linked: linked.ok ? linked.data : null,
licence: licence.ok ? licence.data : null,
backups: backups.ok ? backups.data : null,
});
});
return () => { alive = false; };
}, []);
if (!d) return <p className="text-sm text-gray-500" role="status">Loading…</p>;
const connected = d.linked?.items.filter((l) => l.signsInHere).length ?? 0;
const notConnected = d.linked?.items.filter((l) => !l.signsInHere && l.listed) ?? [];
const lastBackup = d.backups?.items[0]?.createdAt ?? null;
const todo: { text: string; href: string; action: string }[] = [
...(d.deletions ? [{ text: `${d.deletions} ${d.deletions === 1 ? "person has" : "people have"} asked to delete their account.`, href: "/admin/deletions", action: "Review" }] : []),
...(d.licence && !d.licence.connected ? [{ text: "Accounts isn't connected to Cross Code yet, so the church's sites can't find it.", href: "/admin/licence", action: "Connect" }] : []),
...(notConnected.length ? [{ text: `${notConnected.map((l) => l.name).join(", ")} ${notConnected.length === 1 ? "doesn't" : "don't"} sign people in here yet.`, href: "/admin/linked", action: "Connect" }] : []),
...(d.backups?.lastError ? [{ text: "The last backup didn't work.", href: "/admin/backups", action: "See why" }] : []),
];
return (
<div className="space-y-6">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
<Stat icon={<Users className="h-5 w-5" />} label="People with an account" value={d.people ?? "—"} href="/admin/people" detail="Find someone" />
<Stat icon={<UserX className="h-5 w-5" />} label="Deletion requests waiting" value={d.deletions ?? "—"} warn={!!d.deletions} href="/admin/deletions" detail={d.deletions ? "They need your answer" : "None waiting"} />
<Stat icon={<Link2 className="h-5 w-5" />} label="Sites that sign in here" value={d.linked ? `${connected} of ${d.linked.items.length}` : "—"} warn={notConnected.length > 0} href="/admin/linked" detail={d.linked && !d.linked.hubConnected ? "Not connected to the Hub" : "Linked products"} />
<Stat icon={<DatabaseBackup className="h-5 w-5" />} label="Last backup" value={lastBackup ? when(lastBackup) : "None yet"} warn={!!d.backups?.lastError} href="/admin/backups" detail={d.backups ? (d.backups.nightly ? "Every night at 02:00" : "Nightly backups are off") : undefined} />
</div>
<Card>
<Heading icon={todo.length ? <AlertTriangle className="h-4 w-4" /> : <CheckCircle2 className="h-4 w-4" />}>{todo.length ? "Needs you" : "Nothing needs you right now"}</Heading>
{todo.length > 0 ? (
<ul className="divide-y">
{todo.map((t) => (
<li key={t.href} className="flex flex-wrap items-center justify-between gap-3 py-3">
<span className="text-sm text-gray-700">{t.text}</span>
<Link href={t.href} className="inline-flex items-center gap-1 rounded-lg bg-brand px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-dark">{t.action}<ArrowRight className="h-3.5 w-3.5" aria-hidden /></Link>
</li>
))}
</ul>
) : <p className="text-sm text-gray-600">Nothing is waiting for an admin. Anything that is (a deletion request, a site to connect, a backup that failed) shows here.</p>}
</Card>
<Card>
<Heading sub="Every setting, one click away.">All settings</Heading>
<div className="space-y-5">
{ADMIN_GROUPS.filter((g) => g.title).map((g) => (
<div key={g.title}>
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{g.title}</h3>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{g.items.map((n) => {
const Icon = n.icon;
return (
<Link key={n.href} href={n.href} className="flex items-start gap-3 rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand" aria-hidden><Icon className="h-5 w-5" /></span>
<span className="min-w-0">
<span className="block text-sm font-semibold text-gray-900">{n.label}</span>
<span className="mt-0.5 block text-xs text-gray-500">{TILE[n.href]}</span>
</span>
</Link>
);
})}
</div>
</div>
))}
</div>
</Card>
</div>
);
}
// ─── People ──────────────────────────────────────────────────────────────────
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((x) => x[0]!.toUpperCase()).join("") || "?";
const chip = "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium";
function People({ flash }: { flash: Flash }) {
const [q, setQ] = useState("");
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
@@ -93,28 +214,47 @@ function People({ flash }: { flash: Flash }) {
};
return (
<div className="grid gap-6 md:grid-cols-2">
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<Card>
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-3 flex gap-2">
<span className="relative flex-1">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" aria-hidden />
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="w-full rounded-lg border py-2 pl-9 pr-3" />
</span>
<Button type="submit" variant="secondary">Search</Button>
</form>
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
<ul className="divide-y">
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} {list?.total === 1 ? "person" : "people"}</p>
<ul className="-mx-2 divide-y">
{list?.items.map((p) => (
<li key={p.id}>
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
<span className="block text-sm text-gray-500">{p.email}</span>
<button type="button" onClick={() => show(p.id)} aria-current={open?.id === p.id ? "true" : undefined}
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2.5 text-left hover:bg-gray-50 ${open?.id === p.id ? "bg-brand/5" : ""}`}>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand-dark" aria-hidden>{initials(p.name)}</span>
<span className="min-w-0 flex-1">
<span className="flex flex-wrap items-center gap-1.5 font-medium text-gray-900">
{p.name}
{p.role === "admin" && <span className={`${chip} bg-brand/10 text-brand-dark`}>admin</span>}
{p.status !== "active" && <span className={`${chip} bg-amber-50 text-amber-800`}>{p.status}</span>}
</span>
<span className="block truncate text-sm text-gray-500">{p.email}</span>
</span>
<span className="hidden shrink-0 text-right text-xs text-gray-500 sm:block">{p.twoFactor ? <span className="inline-flex items-center gap-1 text-green-700"><ShieldCheck className="h-3.5 w-3.5" aria-hidden />Two-step</span> : null}<span className="block">{p.lastSignInAt ? `Signed in ${when(p.lastSignInAt)}` : "Never signed in"}</span></span>
<ChevronRight className="h-4 w-4 shrink-0 text-gray-300" aria-hidden />
</button>
</li>
))}
</ul>
</Card>
{open && (
<Card>
<Heading sub={open.email}>{open.name}</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
{open ? (
<Card className="lg:sticky lg:top-20">
<div className="mb-4 flex items-center gap-3">
<span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-brand/10 text-sm font-semibold text-brand-dark" aria-hidden>{initials(open.name)}</span>
<div className="min-w-0">
<h2 className="text-lg font-semibold text-gray-900">{open.name}</h2>
<p className="truncate text-xs text-gray-500">{open.email}</p>
</div>
</div>
<dl className="mb-4 grid grid-cols-2 gap-y-1.5 rounded-lg bg-gray-50 p-3 text-sm">
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
@@ -125,12 +265,18 @@ function People({ flash }: { flash: Flash }) {
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => { if (open.status === "active" && !window.confirm(`Deactivate ${open.name}? They're signed out of every site straight away.`)) return; void act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated."); }}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
</div>
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((x, i) => <li key={i}>{x.type} · {when(x.at)} {x.ip && <span className="text-gray-500">· {x.ip}</span>}</li>)}</ul>
{!open.signIns.length && <p className="text-sm text-gray-500">None yet.</p>}
</Card>
) : (
<div className="hidden rounded-xl border border-dashed p-8 text-center text-sm text-gray-500 lg:block">
<Users className="mx-auto mb-2 h-6 w-6 text-gray-300" aria-hidden />
Choose someone to see their account and what you can do for them.
</div>
)}
</div>
);
@@ -140,16 +286,16 @@ function People({ flash }: { flash: Flash }) {
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
function Deletions({ flash }: { flash: Flash }) {
function Deletions({ flash, onChange }: { flash: Flash; onChange: (waiting: number) => void }) {
const [items, setItems] = useState<Deletion[]>([]);
const load = useCallback(async () => {
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
if (r.ok) setItems(r.data.items);
}, []);
if (r.ok) { setItems(r.data.items); onChange(r.data.items.filter((x) => x.status === "waiting_approval").length); }
}, [onChange]);
useExternalEffect(() => { void load(); }, [load]);
return (
<Card>
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
<Heading icon={<UserX className="h-4 w-4" />} sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
<ul className="divide-y">
{items.map((d) => (
@@ -188,7 +334,8 @@ function Church({ flash }: { flash: Flash }) {
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
return (
<Card>
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
<Heading icon={<Building2 className="h-4 w-4" />} sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
{c.branding.logoUrl && <img src={c.branding.logoUrl} alt="The church's logo" className="mb-4 h-12 w-auto rounded border bg-gray-50 p-1" />}
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
@@ -229,7 +376,7 @@ function Linked({ flash }: { flash: Flash }) {
if (!data) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
<Heading icon={<Link2 className="h-4 w-4" />} sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
{!data.hubConnected && <Notice tone="warning">Accounts isn&apos;t connected to the Hub yet (Licence).</Notice>}
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
<ul className="divide-y">
@@ -259,7 +406,7 @@ const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "numb
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
};
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: string[]; title: string; icon: React.ReactNode; sub?: string }) {
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
useExternalEffect(() => {
let alive = true;
@@ -270,6 +417,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
return (
<Card>
<Heading icon={icon} sub={sub}>{title}</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
@@ -280,7 +428,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
else body[k] = String(f.get(k) ?? "");
}
const r = await call("PUT", "/admin/settings", body);
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message);
if (r.ok) flash("success", `${title}: saved.`); else flash("error", r.error.message);
}}>
{keys.map((k) => {
const [label, kind] = SETTING_LABELS[k]!;
@@ -299,6 +447,29 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
);
}
/** 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 };
@@ -317,7 +488,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
return (
<div className="space-y-6">
<Card>
<Heading sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
<Heading icon={<FileText className="h-4 w-4" />} sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
{builtIn && !isBuiltIn && (
<p className="mb-4 text-sm text-gray-600">
The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "}
@@ -338,7 +509,7 @@ function NoticeTab({ flash }: { flash: Flash }) {
</form>
</Card>
<Card>
<Heading sub="As people will see it.">Preview</Heading>
<Heading icon={<Eye className="h-4 w-4" />} sub="As people will see it.">Preview</Heading>
<h3 className="mb-3 text-base font-semibold text-gray-900">{draft.title}</h3>
<div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div>
</Card>
@@ -356,7 +527,7 @@ function Licence({ flash }: { flash: Flash }) {
if (!s) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<Heading icon={<KeyRound className="h-4 w-4" />} sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
@@ -387,7 +558,7 @@ function Audit() {
}, []);
return (
<Card>
<Heading>Audit log</Heading>
<Heading icon={<ScrollText className="h-4 w-4" />}>Audit log</Heading>
<ul className="divide-y text-sm">
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
@@ -0,0 +1,98 @@
"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { CORNERS, FONT_PAIRING_IDS, FONT_PAIRINGS, type Corners, type FontPairing } from "@crosscode/contracts";
import { Button } from "@crosscode/ui";
import { Card, Heading } from "@/components/Panel";
import { call } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Style = { fontPairing: FontPairing | null; corners: Corners | null };
type ChurchStyle = { branding: { style?: Style } };
const CORNER_LABELS: Record<Corners, { name: string; radius: string }> = {
sharp: { name: "Sharp", radius: "0" },
soft: { name: "Soft", radius: "0.5rem" },
round: { name: "Round", radius: "9999px" },
};
/**
* The church's brand style (1.7.0, WEBSITE-1.0-PLAN §3): a font pairing and corners, shared by
* Accounts' pages, the Website and Cross Events. Each option is shown in its own fonts (fonts.css
* is loaded on every page; a pairing's files download only when shown).
*/
export function BrandStyle({ flash }: { flash: (tone: "success" | "error", text: string) => void }) {
const router = useRouter();
const [saved, setSaved] = useState<Style | null>(null);
const [style, setStyle] = useState<Style>({ fontPairing: null, corners: null });
const [busy, setBusy] = useState(false);
useExternalEffect(() => {
let alive = true;
call<ChurchStyle>("GET", "/admin/church").then((r) => {
if (!alive || !r.ok) return;
const s = { fontPairing: r.data.branding.style?.fontPairing ?? null, corners: r.data.branding.style?.corners ?? null };
setSaved(s);
setStyle(s);
});
return () => { alive = false; };
}, []);
if (!saved) return null;
const changed = saved.fontPairing !== style.fontPairing || saved.corners !== style.corners;
const option = (selected: boolean) => `block cursor-pointer rounded-xl border p-4 transition focus-within:ring-2 focus-within:ring-brand/50 ${selected ? "border-brand bg-brand/5 ring-1 ring-brand" : "border-gray-200 hover:border-gray-300"}`;
return (
<Card className="mt-6">
<Heading sub="How the church's sites look: these sign-in pages, the website and Cross Events' public pages. Colours and logo are above.">Brand style</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
const r = await call<ChurchStyle>("PUT", "/admin/church", { branding: { style } });
setBusy(false);
if (r.ok) {
setSaved(style);
flash("success", "Saved. The church's sites use the new style.");
router.refresh();
} else flash("error", r.error.message);
}}>
<fieldset className="mb-6">
<legend className="mb-1 text-sm font-semibold text-gray-900">Fonts</legend>
<p className="mb-3 text-sm text-gray-600">A font for headings and one for text. The website&apos;s template recommends three, but any works.</p>
<div className="grid gap-3 sm:grid-cols-2">
<label className={option(style.fontPairing === null)}>
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === null} onChange={() => setStyle({ ...style, fontPairing: null })} />
<span className="block text-lg font-semibold [font-family:ui-sans-serif,system-ui,sans-serif]">Device fonts</span>
<span className="mt-1 block text-sm text-gray-600 [font-family:ui-sans-serif,system-ui,sans-serif]">Each phone and computer&apos;s own. The website uses its template&apos;s fonts.</span>
</label>
{FONT_PAIRING_IDS.map((id) => {
const p = FONT_PAIRINGS[id];
return (
<label key={id} className={option(style.fontPairing === id)} data-cc-fonts={id}>
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === id} onChange={() => setStyle({ ...style, fontPairing: id })} />
<span className="block text-lg font-semibold [font-family:var(--cc-font-heading)] [font-variation-settings:var(--cc-heading-variation,normal)]">{p.name}: Welcome home</span>
<span className="mt-1 block text-sm text-gray-700 [font-family:var(--cc-font-body)]">{p.feel}. <em>Sundays at 09:00.</em></span>
<span className="mt-2 block text-xs text-gray-500 [font-family:ui-sans-serif,system-ui,sans-serif]">{p.heading.family}{p.body.family !== p.heading.family && ` and ${p.body.family}`}</span>
</label>
);
})}
</div>
</fieldset>
<fieldset className="mb-6">
<legend className="mb-1 text-sm font-semibold text-gray-900">Corners</legend>
<p className="mb-3 text-sm text-gray-600">Of buttons, cards, photos and fields.</p>
<div className="grid grid-cols-3 gap-3">
{CORNERS.map((id) => (
<label key={id} className={option((style.corners ?? "soft") === id)}>
<input type="radio" name="corners" className="sr-only" checked={(style.corners ?? "soft") === id} onChange={() => setStyle({ ...style, corners: id })} />
<span className="mb-2 block h-8 w-full bg-brand" style={{ borderRadius: CORNER_LABELS[id].radius }} aria-hidden />
<span className="block text-sm font-medium">{CORNER_LABELS[id].name}</span>
</label>
))}
</div>
</fieldset>
<Button type="submit" busy={busy} disabled={!changed}>Save</Button>
</form>
</Card>
);
}
@@ -7,9 +7,9 @@ export async function generateMetadata({ params }: { params: Promise<{ section:
return { title: ADMIN_SECTIONS[section as AdminSection]?.title ?? "Admin" };
}
/** One section of admin (1.3.0): /admin/deletions, /church, /linked, … (/admin itself is People). */
/** One section of admin (1.3.0): /admin/people, /deletions, /church, … (1.8.0: /admin itself is the overview). */
export default async function AdminSectionPage({ params }: { params: Promise<{ section: string }> }) {
const { section } = await params;
if (section === "people" || !(section in ADMIN_SECTIONS)) notFound();
if (section === "overview" || !(section in ADMIN_SECTIONS)) notFound();
return <Admin section={section as AdminSection} />;
}
@@ -3,5 +3,5 @@ import { Admin } from "./Admin";
export const metadata = { title: "Admin" };
export default function AdminPage() {
return <Admin />;
return <Admin section="overview" />;
}
@@ -2,7 +2,8 @@
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call } from "@/lib/api";
@@ -12,7 +13,7 @@ export function Forgot({ uid }: { uid: string | null }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
{sent ? (
@@ -32,6 +33,6 @@ export function Forgot({ uid }: { uid: string | null }) {
)}
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
</Card>
</Shell>
</PublicShell>
);
}
@@ -10,4 +10,11 @@
body {
@apply bg-gray-50 text-gray-900 antialiased;
/* 1.7.0: the church's font pairing when it has one (@crosscode/ui fonts.css), else the system font. */
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");
}
h1, h2, h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
+7 -4
View File
@@ -1,8 +1,10 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { BrandingProvider } from "@/components/BrandingProvider";
import { loadBranding, rgbVars } from "@/lib/branding";
import { loadBranding, loadChurch, rgbVars } from "@/lib/branding";
export async function generateMetadata(): Promise<Metadata> {
const b = await loadBranding();
@@ -12,15 +14,16 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get("x-nonce") ?? undefined;
const b = await loadBranding();
const [b, church] = await Promise.all([loadBranding(), loadChurch()]);
const vars = rgbVars(b.colours.primary);
// 1.7.0: the church's font pairing and corners (fonts.css), shared with its other sites.
return (
<html lang="en-ZA">
<html lang="en-ZA" {...brandAttributes(b.style)}>
<head>
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
</head>
<body>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded, church }}>
{children}
</BrandingProvider>
</body>
@@ -2,7 +2,8 @@
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
@@ -11,7 +12,7 @@ export function Reset({ token }: { token: string | null }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
{error && <Notice tone="error">{error}</Notice>}
@@ -29,6 +30,6 @@ export function Reset({ token }: { token: string | null }) {
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
</form>
</Card>
</Shell>
</PublicShell>
);
}
@@ -1,18 +1,19 @@
"use client";
import { LogOut } from "lucide-react";
import { Card, Heading, Shell } from "@crosscode/ui";
import { Card, Heading } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { selfSignIn } from "@/lib/api";
export default function SignedOutPage() {
const branding = useBranding();
return (
<Shell branding={branding}>
<PublicShell>
<Card>
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You&apos;re signed out</Heading>
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
</Card>
</Shell>
</PublicShell>
);
}
@@ -3,7 +3,8 @@
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
import React, { useState } from "react";
import QRCode from "qrcode";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { Button, Card, Checkbox, Field, Heading, Notice } from "@crosscode/ui";
import { PublicShell } from "@/components/PublicShell";
import { useBranding } from "@/components/BrandingProvider";
import { NoticeText } from "@/components/NoticeText";
import { call, type ApiError } from "@/lib/api";
@@ -82,7 +83,7 @@ export function SignIn({ uid }: { uid: string }) {
return r;
};
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
const frame = (children: React.ReactNode) => <PublicShell><Card>{children}</Card></PublicShell>;
if (codes) {
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
@@ -12,7 +12,7 @@ import { useBranding } from "@/components/BrandingProvider";
/** Who's signed in, as the shell shows them (null: a public page such as the privacy notice). */
export type ShellUser = { name: string; email: string; role: "member" | "admin" };
type NavItem = { href: string; label: string; icon: LucideIcon };
export type NavItem = { href: string; label: string; icon: LucideIcon };
export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account", label: "Overview", icon: LayoutDashboard },
@@ -22,19 +22,21 @@ export const ACCOUNT_NAV: NavItem[] = [
{ href: "/account/activity", label: "Activity", icon: Activity },
];
export const ADMIN_NAV: NavItem[] = [
{ href: "/admin", label: "People", icon: Users },
{ href: "/admin/deletions", label: "Deletion requests", icon: UserX },
{ href: "/admin/church", label: "Church profile", icon: Building2 },
{ href: "/admin/linked", label: "Linked products", icon: Link2 },
{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn },
{ href: "/admin/messages", label: "Email and WhatsApp", icon: Mail },
{ href: "/admin/notice", label: "Privacy notice", icon: FileText },
{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup },
{ href: "/admin/jobs", label: "Background jobs", icon: Timer },
{ href: "/admin/licence", label: "Licence", icon: KeyRound },
{ href: "/admin/audit", label: "Audit log", icon: ScrollText },
/** 1.8.0: the admin's sections in groups, as Cross Events' settings, with the overview first. */
export const ADMIN_GROUPS: { title: string | null; items: NavItem[] }[] = [
{ title: null, items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] },
{ title: "People", items: [{ href: "/admin/people", label: "People", icon: Users }, { href: "/admin/deletions", label: "Deletion requests", icon: UserX }] },
{ title: "Church", items: [{ href: "/admin/church", label: "Church profile", icon: Building2 }, { href: "/admin/linked", label: "Linked products", icon: Link2 }] },
{
title: "Signing in",
items: [{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn }, { href: "/admin/messages", label: "Email and WhatsApp", icon: Mail }, { href: "/admin/notice", label: "Privacy notice", icon: FileText }],
},
{
title: "System",
items: [{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup }, { href: "/admin/jobs", label: "Background jobs", icon: Timer }, { href: "/admin/licence", label: "Licence", icon: KeyRound }, { href: "/admin/audit", label: "Audit log", icon: ScrollText }],
},
];
export const ADMIN_NAV: NavItem[] = ADMIN_GROUPS.flatMap((g) => g.items);
/** Signs out of Accounts and every site of the church (RP-initiated logout), ending on /signed-out. */
export function signOutHref() {
@@ -53,28 +55,59 @@ function RoleBadge({ role }: { role: ShellUser["role"] }) {
: <span className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600">Member</span>;
}
function NavList({ title, items, active, onNavigate }: { title: string; items: NavItem[]; active: string; onNavigate?: () => void }) {
/** Counts beside a section (deletion requests waiting, say), by its address. */
export type Badges = Record<string, number>;
function NavLinks({ items, active, badges, onNavigate }: { items: NavItem[]; active: string; badges?: Badges; onNavigate?: () => void }) {
return (
<ul className="space-y-0.5">
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
const n = badges?.[l.href] ?? 0;
return (
<li key={l.href}>
<Link href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
<span className="flex-1">{l.label}</span>
{n > 0 && <span className="rounded-full bg-amber-100 px-1.5 text-xs font-semibold text-amber-900">{n}<span className="sr-only"> waiting</span></span>}
</Link>
</li>
);
})}
</ul>
);
}
function AccountNav({ active, onNavigate }: { active: string; onNavigate?: () => void }) {
return (
<div className="mb-6">
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-400">{title}</p>
<nav className="space-y-1" aria-label={title}>
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
return (
<Link key={l.href} href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
{l.label}
</Link>
);
})}
</nav>
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Your account</p>
<nav aria-label="Your account"><NavLinks items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} /></nav>
</div>
);
}
function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: string; onNavigate?: () => void }) {
function AdminNav({ active, badges, onNavigate }: { active: string; badges?: Badges; onNavigate?: () => void }) {
return (
<nav aria-label="Admin" className="mb-6 space-y-5">
{ADMIN_GROUPS.map((g, i) => (
<div key={g.title ?? i}>
<p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{g.title ?? "Admin"}</p>
<NavLinks items={g.items} active={active} badges={badges} onNavigate={onNavigate} />
</div>
))}
</nav>
);
}
/**
* The sidebar: who's signed in, then the sections of the part you're in (1.8.0: your account or
* admin, not both at once; the bar across the top switches). In the phone menu, both.
*/
function SidebarContent({ me, active, badges, both, onNavigate }: { me: ShellUser; active: string; badges?: Badges; both?: boolean; onNavigate?: () => void }) {
const inAdmin = me.role === "admin" && active.startsWith("/admin");
return (
<>
<div className="mb-6 flex items-center gap-3 px-1">
@@ -84,8 +117,14 @@ function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: str
<RoleBadge role={me.role} />
</div>
</div>
<NavList title="Your account" items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} />
{me.role === "admin" && <NavList title="Admin" items={ADMIN_NAV} active={active} onNavigate={onNavigate} />}
{(both || !inAdmin) && <AccountNav active={active} onNavigate={onNavigate} />}
{me.role === "admin" && (both || inAdmin) && <AdminNav active={active} badges={badges} onNavigate={onNavigate} />}
{!both && me.role === "admin" && (
<Link href={inAdmin ? "/account" : "/admin"} className="flex items-center gap-2 rounded-lg border border-dashed px-3 py-2 text-sm text-gray-600 hover:border-brand/40 hover:text-brand-dark">
{inAdmin ? <User className="h-4 w-4" aria-hidden /> : <ShieldCheck className="h-4 w-4" aria-hidden />}
{inAdmin ? "Go to your account" : "Go to admin"}
</Link>
)}
</>
);
}
@@ -95,7 +134,7 @@ function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: str
* and name across the top, a sidebar of sections, the page on a light grey, and a dark footer.
* Without `me` (a public page) there's no sidebar. `active` is the current section's address.
*/
export function AppShell({ me, active = "", children }: { me: ShellUser | null; active?: string; children: React.ReactNode }) {
export function AppShell({ me, active = "", badges, children }: { me: ShellUser | null; active?: string; badges?: Badges; children: React.ReactNode }) {
const b = useBranding();
const [open, setOpen] = useState(false);
const top = "text-sm border-b-2 pb-0.5 transition-colors";
@@ -131,7 +170,7 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
<button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} />
<div className="absolute inset-y-0 left-0 flex w-72 max-w-[85vw] flex-col overflow-y-auto bg-white p-4 shadow-xl">
<button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="mb-2 self-end rounded-md p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button>
<SidebarContent me={me} active={active} onNavigate={() => setOpen(false)} />
<SidebarContent me={me} active={active} badges={badges} both onNavigate={() => setOpen(false)} />
<a href="/signed-out" onClick={(e) => { e.preventDefault(); window.location.assign(signOutHref()); }} className="mt-auto flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50">
<LogOut className="h-4 w-4" aria-hidden /> Sign out
</a>
@@ -142,7 +181,7 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
<div className="mx-auto flex w-full max-w-7xl flex-1">
{me && (
<aside className="hidden w-64 shrink-0 border-r bg-white p-4 md:block">
<div className="sticky top-20"><SidebarContent me={me} active={active} /></div>
<div className="sticky top-20"><SidebarContent me={me} active={active} badges={badges} /></div>
</aside>
)}
<main id="main" className="min-w-0 flex-1 p-4 sm:p-6">{children}</main>
@@ -159,12 +198,15 @@ export function AppShell({ me, active = "", children }: { me: ShellUser | null;
);
}
/** A page's title and a line under it, at the top of the main column. */
export function PageTitle({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) {
/** A page's title and a line under it, at the top of the main column; with the section's icon. */
export function PageTitle({ children, sub, icon: Icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: LucideIcon }) {
return (
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
<div className="mb-6 flex items-start gap-3">
{Icon && <span className="mt-0.5 hidden h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand sm:flex" aria-hidden><Icon className="h-5 w-5" /></span>}
<div className="min-w-0">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
</div>
</div>
);
}
@@ -1,8 +1,10 @@
"use client";
import React, { createContext, useContext } from "react";
import type { FooterChurch } from "@crosscode/ui";
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
/** `church` (1.7.0): the profile for the shared footer, null when it couldn't be loaded. */
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean; church?: FooterChurch | null };
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
@@ -0,0 +1,16 @@
"use client";
import React from "react";
import { ChurchFooter, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
/**
* The frame of the public pages (sign in, forgot, reset, signed out, confirm email) with the
* church's shared footer (1.7.0, WEBSITE-1.0-PLAN §9): its service times, contact and links to its
* other sites, as on the Website and Cross Events.
*/
export function PublicShell({ children }: { children: React.ReactNode }) {
const branding = useBranding();
const footer = branding.church ? <ChurchFooter church={branding.church} current="accounts" privacyUrl="/privacy" /> : undefined;
return <Shell branding={branding} footer={footer}>{children}</Shell>;
}
@@ -1,9 +1,13 @@
import type { FooterChurch } from "@crosscode/ui";
/** The church's branding from the backend, for the server-rendered frame of every page. */
export type BrandingData = {
name: string;
shortName: string | null;
logoUrl: string | null;
colours: { primary: string; accent: string | null };
/** 1.7.0: the font pairing and corners (null: not picked). */
style?: { fontPairing: string | null; corners: string | null };
signupEnabled: boolean;
setupNeeded: boolean;
};
@@ -20,6 +24,17 @@ export async function loadBranding(): Promise<BrandingData> {
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
}
/** The church profile (`crosscode.church/1`) for the shared footer (1.7.0), or null while it can't be had. */
export async function loadChurch(): Promise<FooterChurch | null> {
try {
const res = await fetch(`${api}/api/church/v1`, { next: { revalidate: 60 } });
if (res.ok) return (await res.json()) as FooterChurch;
} catch {
// As loadBranding: the page works without it.
}
return null;
}
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
export function rgbVars(hex: string): { brand: string; dark: string } {
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
+17 -12
View File
@@ -1,15 +1,20 @@
/** The admin's sections (1.3.0): one address each, in the sidebar (components/AppShell.tsx). */
/**
* The admin's sections: one address each, in groups down the side (components/AppShell.tsx), and a
* tile each on the overview. 1.8.0: /admin is the overview (as Cross Events' admin dashboard);
* People moved to /admin/people.
*/
export const ADMIN_SECTIONS = {
people: { path: "/admin", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site." },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account." },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites." },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here." },
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in." },
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." },
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away." },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." },
overview: { path: "/admin", title: "Admin", sub: "How Accounts stands, what needs you, and every setting.", tile: "" },
people: { path: "/admin/people", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site.", tile: "Find someone, reset their two-step sign-in, make an admin" },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account.", tile: "Approve or cancel people's requests to delete their account" },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites.", tile: "Name, logo, colours and contact details for every site" },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here.", tile: "The sites and apps that sign people in here" },
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in.", tile: "Who can make an account, two-step sign-in, staying signed in" },
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices.", tile: "How sign-in codes and password links are sent" },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes.", tile: "What people read before they first sign in" },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server.", tile: "Back up now, download a copy, how many to keep" },
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away.", tile: "What runs on a schedule, and when" },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code.", tile: "The connection to Cross Code" },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here.", tile: "Who changed what, and when" },
} as const;
export type AdminSection = keyof typeof ADMIN_SECTIONS;
+81
View File
@@ -0,0 +1,81 @@
# What's new in the server agent
What each version of the Cross Code server agent changes, for whoever runs the Hub. The Hub shows
these notes on its Releases page and when you pick a version under Update agent.
<!--
How this file is used: the Cross Code Hub reads it from main every 15 minutes (release source
"Server agent", tags agent@1.2.3) and shows a section only once its version is tagged, so write it
before tagging; fixes to old sections show straight away. Each version is a "## 1.2.3" heading; add
"— urgent" (or "security") to the heading for a security or serious bug fix. Under it, lines
starting with "- " show as a list and other lines as paragraphs.
Write for the person updating servers: what the agent can now do from the Hub, and which Hub or
contracts version needs it. The developer log is the commit history of apps/agent.
-->
## 1.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
those go, and the church keeps the others. Naming every product it still has removes the whole
church, so the last product to go takes the church with it. Before, uninstalling a church's Cross
Events also removed its Accounts.
- The Hub (2.12.0 and later) uninstalls one product only on servers with this agent; older agents
can only remove the whole church.
## 1.4.0
- **frp's config from the Hub.** The agent finds frps's config (central server) or frpc's (church
server) wherever it is: the path set on the Hub, the `-c` in the systemd unit, or the usual places.
It reads INI and TOML.
- **Changing it from the Hub:** the agent checks the new file with `frp* verify`, keeps a backup,
restarts frp if asked, and puts the old file back if frp doesn't start. Secret values never leave
the server.
- **Ports checked before an install:** the Hub asks this server and the central server which ports
are free, so a new install gets ports free on both.
- Needed for frp config on a server's page and port checks (Hub 2.11.0).
## 1.3.1
- **Fix:** 1.3.0 reported itself as 1.2.0, so the Hub refused its .env jobs. It now reports its
real version. Install this instead of 1.3.0.
## 1.3.0
- **A site's .env from the Hub.** The agent reads an install's .env (secret values hidden) and
changes it: one file at a time, rebuilding the site when its frontend settings changed,
restarting it, and putting the old file back if the site doesn't answer.
- Needed for the Settings (.env) tab on an install's page (Hub 2.8.0).
## 1.2.0
- **Demo data from the Hub.** The agent loads a demo profile onto a site marked as a demo: a backup
first, then the demo data, keeping one admin account.
- Needed for demo sites (Hub 2.4.0).
## 1.1.1
- **Fix:** the server's stats now keep going while a long job runs. Before, a 30-minute install
stopped them and the Hub alerted that the server was down.
- **Fix:** 1.1.0 reported itself as 1.0.1; it now reports its real version.
## 1.1.0
- **Accounts installs.** The agent installs Accounts, and adds a product next to a church's others
on the same server (with the ports and release the Hub chose).
## 1.0.1
- **Fix:** on the central server, Check status failed (it has no `crosscode` script). It now answers
with its own stats, including whether frps is running.
## 1.0.0
- **The first server agent.** It polls the Hub every 30 seconds for signed jobs, runs the
`crosscode` script for them (install, update, status, export, uninstall), sends the results, and
sends the server's stats every minute. It listens on no port: every request goes out to the Hub.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.4.0",
"version": "1.6.0",
"private": true,
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
"license": "UNLICENSED",
+7 -4
View File
@@ -59,14 +59,17 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
return out;
}
case "seed-demo":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
// 1.6.0: the Website's demo names the product; Events' (no product) keeps its old form.
return ["demo", job.args.church, ...(job.args.product === "website" ? ["website"] : []), "--profile", job.args.profile,
...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, "--out", opts.exportFile];
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
case "uninstall":
return ["uninstall", job.args.church, "--confirm", job.args.church];
// 1.5.0: only the products named go (the church keeps its others); none named: the church.
return ["uninstall", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
case "purge":
return ["purge", job.args.church, "--confirm", job.args.church];
return ["purge", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
case "status":
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
case "update-agent":
+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.4.0";
export const AGENT_VERSION = "1.6.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+7
View File
@@ -36,6 +36,10 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
// 1.5.0: one product of the church.
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope", products: ["events"] } }))).toEqual(["uninstall", "hope", "events", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope", products: ["events"] } }))).toEqual(["purge", "hope", "events", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh", products: ["accounts"] } }), { exportFile: "/x/e.zip" })).toEqual(["export", "hope", "accounts", "--out", "/x/e.zip"]);
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
});
@@ -43,6 +47,9 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } })))
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
// 1.6.0: the Website's demo.
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant" } }))).toEqual(["demo", "hope", "website", "--profile", "bold-plant"]);
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
});
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
+92
View File
@@ -5,6 +5,98 @@ 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.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.
### Fixed
- **A product installed after this site's last heartbeat can connect straight away.** A connect
(in either direction) was refused while the other install wasn't in the cached copy of the Hub's
list, refreshed every 15 minutes. So a new Church Website couldn't connect for the event feed
until then. Now, for an install it doesn't know, the site sends the Hub a heartbeat to get a fresh
list and looks again (at most one such heartbeat a minute, so unknown installs can't make it call
the Hub more often). Same change as Accounts 1.7.1 and Website 1.0.2.
## [3.7.0] - 2026-11-24
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). **Requires Accounts 1.7.0**
(WHATS-NEW.md says so, and the Hub updates Accounts first) for the brand style. No migrations, no
new settings.
### Added
- **The church's fonts and corners on the public pages.** The backend reads the church profile from
Accounts (`GET /api/church/v1`, kept for 10 minutes; `src/accounts/church.ts`) and the public
pages get it from the new `GET /api/v2/church` (public). `<html>` gets `brandAttributes(style)`
from `@crosscode/ui` and the root layout imports `@crosscode/ui/fonts.css` (self-hosted, so no
font is loaded from another site). Body text and h1–h3 use `--cc-font-body` and
`--cc-font-heading` when the church picked a pairing, and `--radius` follows the corner style
(`soft` is 0.5rem, the same as before). The dashboard and setup screens (`data-cc-staff`) keep
the system fonts and 0.5rem.
- **`church.changed` from Accounts** at `POST /api/church/v1/changed` (signed with the Accounts
link, `LINK_HEADERS`): the profile is fetched again on the next page. Before 3.7.0 this answered
404 and Accounts kept retrying for a week.
- **The shared church footer** (`ChurchFooter`, `@crosscode/ui` 0.3.0) on the public pages when
Accounts is connected: name and logo, service times, address, contact, social links and links
to the church's other sites and the privacy notice, with Terms of Use and cookie settings below.
Without Accounts, and on the dashboard (`<Footer plain />`), the footer is as before.
- **Links to the church's other sites** in the header of the public pages (its Website, later its
App), from the profile's `links`.
### Changed
- `@crosscode/ui` 0.3.0: `ChurchFooter` takes `bottom` (a product's own links after the copyright).
- Frontend: `transpilePackages: ["@crosscode/ui"]`; Tailwind scans `packages/ui/src` and has
`brand` (brand-700) for the shared footer.
## [3.6.1] - 2026-11-20
### Fixed
+29
View File
@@ -12,6 +12,35 @@ 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.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
Cross Events events as soon as it's installed, instead of after up to 15 minutes.
## 3.7.0 — requires accounts 1.7.0
- **Your public pages look like the rest of your church's sites.** With sign-in through your
church's Accounts, the event pages use the fonts and corner style picked under Accounts → Admin →
Brand style (as your sign-in pages, and later your church website, do), and a new footer shows your service times,
address, contact details, social links and links to your other sites. The dashboard looks the same
as before.
## 3.6.1
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
+5 -1
View File
@@ -63,9 +63,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.
---
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.6.1",
"version": "3.8.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",
@@ -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;
}
}
/**
@@ -0,0 +1,67 @@
/**
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand
* style (fonts and corners) and what the shared footer shows (service times, address, contact,
* social, the church's other sites). Accounts owns it and serves it publicly at
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`).
*
* Fetched again after 10 minutes, or at once when Accounts sends `church.changed`
* (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last
* copy is kept and it's tried again after a minute; a site without Accounts has none, and its
* pages look as they always have.
*/
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
import { accountsLink } from './client';
const FRESH_MS = 10 * 60e3;
const RETRY_MS = 60e3;
const TIMEOUT_MS = 5000;
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
let cached: Cached | null = null;
let pending: Promise<Church | null> | null = null;
async function fetchProfile(accountsUrl: string): Promise<Church> {
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
const parsed = churchSchema.safeParse(await res.json());
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
return parsed.data;
}
/** The church's profile, or null when Accounts isn't connected or hasn't answered yet. Never throws. */
export async function churchProfile(): Promise<Church | null> {
let link;
try {
link = await accountsLink();
} catch {
return cached?.church ?? null;
}
if (!link) return null;
const url = link.url;
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
if (!pending) {
const last = cached?.url === url ? cached.church : null;
pending = fetchProfile(url)
.then((church) => {
cached = { url, church, at: Date.now(), ok: true };
return church;
}, (e: Error) => {
console.warn('[church] profile not fetched from Accounts:', e.message);
cached = { url, church: last, at: Date.now(), ok: false };
return last;
})
.finally(() => { pending = null; });
}
return pending;
}
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */
export function churchChanged(): void {
if (cached) cached = { ...cached, at: 0 };
}
/** Tests: start with nothing. */
export function resetChurchProfile(): void {
cached = null;
pending = null;
}
+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;
}
}
@@ -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 };
}
+32 -4
View File
@@ -35,6 +35,34 @@ export class LinkError extends Error {
}
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
let refresh: { at: number; run: Promise<unknown> } | null = null;
/** For tests. */
export function forgetRefresh(): void {
refresh = null;
}
/**
* 3.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat, like a new Church Website), the site asks the Hub for a fresh
* list with a heartbeat and looks again, instead of refusing for up to 15 minutes. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make this site call the
* Hub more often than that.
*/
async function listedOrRefreshed(installId: string, now: Date) {
const found = await listedProduct(installId);
if (found) return found;
if (!refresh || now.getTime() - refresh.at >= REFRESH_EVERY_MS) {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS, and hub/client.js needs this module's siblings
const run = Promise.resolve().then(() => require('../hub/client').heartbeat())
.catch((e: Error) => console.warn('[links] Asking the Hub for a fresh list failed:', e?.message || e));
refresh = { at: now.getTime(), run };
}
await refresh.run;
return listedProduct(installId);
}
type Self = { installId: string; url: string; privateKeyPem: string };
@@ -81,8 +109,8 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) {
const sibling = await listedProduct(installId);
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(installId, now);
if (!sibling) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self();
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -123,9 +151,9 @@ export async function acceptConnect(body: unknown, ip: string | null, now = new
const m = parsed.data;
const me = await self();
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(m.from.installId);
const sibling = await listedOrRefreshed(m.from.installId, now);
if (!sibling || sibling.product !== m.from.product) {
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (this site asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
+22 -1
View File
@@ -4,6 +4,7 @@
*
* GET /api/feed/v1/events?updatedSince= crosscode.event-feed/1 (public; "Publish my events")
* POST /api/feed/v1/changed event.changed from a linked product (LINK_HEADERS)
* POST /api/church/v1/changed church.changed from the church's Accounts (3.7.0)
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
*
@@ -11,11 +12,12 @@
*/
import express, { type Request, type Response, type Router } from 'express';
import rateLimit from 'express-rate-limit';
import { eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
import { hubInstallId, publishOn } from '../feed/context';
import { feedResponse, lastRefresh, refreshOnce } from '../feed/entries';
import { acceptConnect, acceptDisconnect, LinkError } from './connect';
import { churchChanged } from '../accounts/church';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
@@ -74,6 +76,25 @@ export function crossProductRouter(): Router {
}
});
// 3.7.0: the church profile changed in Accounts (its brand style, footer details): fetch it again.
router.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), limiter(300), express.raw({ type: () => true, limit: '16kb' }), async (req, res) => {
try {
const sender = String(req.get(LINK_HEADERS.sender) || '');
const link = sender ? await prisma.productLink.findUnique({ where: { installId: sender } }) : null;
if (!link || link.product !== 'accounts') return fail(res, 404, 'NOT_LINKED', 'This site has no link with that Accounts.');
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const check = verify({ secret: decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody });
if (!check.ok) return fail(res, 401, check.code, "The signature doesn't match this link.");
let body: unknown;
try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; }
if (!churchChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', "That isn't a church.changed message.");
churchChanged();
return res.status(202).json({ accepted: true });
} catch (e) {
return sendError(res, e);
}
});
router.post(LINK_PATHS.connect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
try {
return res.json(await acceptConnect(req.body, getClientIp(req)));
+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 || ''));
}
/**
@@ -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 };
+1
View File
@@ -26,6 +26,7 @@ import './resources/ai';
import './resources/feedback';
import './resources/linkedProducts';
import './resources/signIn';
import './resources/church';
const pkg = require('../../package.json') as { version: string };
@@ -0,0 +1,23 @@
import { churchSchema } from '@crosscode/contracts';
import { defineRoute } from '../route';
import { single } from '../paging';
import { churchProfile } from '../../accounts/church';
/**
* The church profile for the public pages (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): its brand style
* (fonts, corners) and the shared footer's details, from the church's Accounts
* (src/accounts/church.ts). null when Accounts isn't connected.
*/
export const getChurch = defineRoute({
method: 'get',
path: '/church',
tag: 'Site',
summary: "The church's profile",
description: "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.",
access: 'public',
response: single(churchSchema.nullable()),
async handler({ res }) {
res.setHeader('Cache-Control', 'public, max-age=60');
return { data: await churchProfile() };
},
});
@@ -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);
});
@@ -0,0 +1,140 @@
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9): the church profile from Accounts for the public pages (its
// brand style and the shared footer), kept in memory and fetched again on church.changed.
import fs from 'fs';
import path from 'path';
import express from 'express';
import request from 'supertest';
type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date };
const mockLinks: Link[] = [];
jest.mock('../src/config/db', () => ({
productLink: {
findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null,
findUnique: async ({ where }: { where: { installId: string } }) => mockLinks.find((l) => l.installId === where.installId) ?? null,
},
}));
jest.mock('../src/jobs', () => ({ enqueueTask: async () => ({ queued: true }) }));
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
import { CHURCH_PATHS } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import { churchProfile, resetChurchProfile } from '../src/accounts/church';
import { crossProductRouter } from '../src/links/routes';
import { getChurch } from '../src/v2/resources/church';
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS
const { encrypt } = require('../src/utils/encryption') as { encrypt(v: string): string };
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
const sample = (name: string) => JSON.parse(fs.readFileSync(path.join(SAMPLES, name), 'utf8'));
const ACCOUNTS_ID = '5c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f';
const SECRET = 'link-secret-for-the-test-0123456789';
let profile = sample('church.json');
let answers: (number | 'down')[] = [];
let fetches = 0;
const realFetch = global.fetch;
beforeAll(() => {
global.fetch = (async (url: string) => {
fetches++;
expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`);
const next = answers.shift() ?? 200;
if (next === 'down') throw new Error('connect ECONNREFUSED');
return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } });
}) as typeof fetch;
});
afterAll(() => { global.fetch = realFetch; });
beforeEach(() => {
resetChurchProfile();
mockLinks.length = 0;
answers = [];
fetches = 0;
profile = sample('church.json');
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => { jest.restoreAllMocks(); });
const connectAccounts = () => mockLinks.push({ installId: ACCOUNTS_ID, product: 'accounts', url: 'https://accounts.hope.test/', secret: encrypt(SECRET), updatedAt: new Date() });
function app() {
const a = express();
a.use('/api', crossProductRouter());
return a;
}
function changed(body: object, { from = ACCOUNTS_ID, secret = SECRET } = {}) {
const raw = JSON.stringify(body);
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret, rawBody: raw });
return request(app()).post(CHURCH_PATHS.changed).set({ 'content-type': 'application/json', ...headers }).send(raw);
}
describe('the church profile', () => {
test('none without Accounts, and nothing is fetched', async () => {
expect(await churchProfile()).toBeNull();
expect(fetches).toBe(0);
});
test("fetched from the church's Accounts, with its brand style, and kept", async () => {
connectAccounts();
const c = await churchProfile();
expect(c?.branding.style).toEqual({ fontPairing: 'warm', corners: 'soft' });
expect(c?.name).toBe(profile.name);
await churchProfile();
expect(fetches).toBe(1);
});
test('a pairing this version doesn\'t know reads as none, so the page keeps its fonts', async () => {
connectAccounts();
profile.branding.style = { fontPairing: 'from-the-future', corners: 'round' };
expect((await churchProfile())?.branding.style).toEqual({ fontPairing: null, corners: 'round' });
});
test('Accounts down: none at first, then the last copy is kept while it is down', async () => {
connectAccounts();
answers = ['down'];
expect(await churchProfile()).toBeNull();
resetChurchProfile();
expect((await churchProfile())?.name).toBe(profile.name);
});
test('a profile that isn\'t crosscode.church/1 isn\'t used', async () => {
connectAccounts();
profile = { hello: 'world' };
expect(await churchProfile()).toBeNull();
});
test('GET /api/v2/church answers it, cacheable for a minute', async () => {
connectAccounts();
const headers: Record<string, string> = {};
const res = { setHeader: (k: string, v: string) => { headers[k] = v; } };
const out = await getChurch.handler({ res } as never);
expect(getChurch.response.safeParse(out).success).toBe(true);
expect((out as { data: { name: string } }).data.name).toBe(profile.name);
expect(headers['Cache-Control']).toBe('public, max-age=60');
});
});
describe('church.changed from Accounts', () => {
test('fetches the profile again (the last copy until then)', async () => {
connectAccounts();
await churchProfile();
profile.branding.style = { fontPairing: 'classic', corners: 'sharp' };
expect((await churchProfile())?.branding.style?.fontPairing).toBe('warm');
const res = await changed(sample('church-changed.json'));
expect(res.status).toBe(202);
expect((await churchProfile())?.branding.style).toEqual({ fontPairing: 'classic', corners: 'sharp' });
expect(fetches).toBe(2);
});
test('refuses a wrong signature, a sender that isn\'t Accounts and a body that isn\'t church.changed', async () => {
connectAccounts();
mockLinks.push({ installId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', product: 'website', url: 'https://www.hope.test', secret: encrypt(SECRET), updatedAt: new Date() });
expect((await changed(sample('church-changed.json'), { secret: 'not-the-secret-at-all-0123456789' })).status).toBe(401);
expect((await changed(sample('church-changed.json'), { from: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' })).status).toBe(404);
const bad = await changed({ type: 'something.else' });
expect(bad.status).toBe(400);
expect(bad.body.code).toBe('INVALID_REQUEST');
});
});
@@ -87,6 +87,7 @@ const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
async function setUpSite({ linked = true } = {}) {
db.reset();
store.forgetKeyPair();
connect.forgetRefresh();
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
@@ -286,6 +287,29 @@ describe('Connect from a linked product', () => {
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
});
test('3.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
await store.saveLinkedProducts([]);
const hubClient = require('../src/hub/client');
let listed = [{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }];
const spy = jest.spyOn(hubClient, 'heartbeat').mockImplementation(async () => { await store.saveLinkedProducts(listed); return { ok: true }; });
try {
await connect.acceptConnect(connectMessage(), null, new Date());
expect(spy).toHaveBeenCalledTimes(1);
expect(db.t.productLink.get(WEBSITE_ID)).toMatchObject({ product: 'website' });
// An install the Hub doesn't list: refused, and the Hub isn't asked again within the minute.
listed = [];
await store.saveLinkedProducts([]);
const t = new Date();
await expect(connect.acceptConnect(connectMessage(), null, t)).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(1);
await expect(connect.acceptConnect(connectMessage(), null, new Date(t.getTime() + 61_000))).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(2);
} finally {
spy.mockRestore();
}
});
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
await connect.acceptConnect(connectMessage(), null);
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
@@ -375,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();
@@ -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');
});
});
+117
View File
@@ -0,0 +1,117 @@
import path from "path";
import AxeBuilder from "@axe-core/playwright";
import { test, expect, loginAs, seed } from "./fixtures";
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9 and §13): with the church's Accounts connected, the public
// pages use the church's fonts and corners from its profile and the shared church footer, as the
// Website and Accounts' own pages do. The dashboard stays as it is. Accounts runs in memory
// (e2e/support/accounts-server.mts); afterwards the link is removed, so the other specs see the
// site as before.
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
const backend = path.join(__dirname, "..", "backend");
require(require.resolve("dotenv", { paths: [backend] })).config({ path: path.join(backend, ".env") });
const { Client } = require(require.resolve("pg", { paths: [backend] }));
const { e2eDatabaseUrl } = require("./support/db-url");
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
const { encrypt } = require(path.join(backend, "src", "utils", "encryption"));
/* eslint-enable @typescript-eslint/no-require-imports */
const ACCOUNTS_API = "http://127.0.0.1:5221";
const ACCOUNTS_ID = "7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b";
const TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
async function sql(text: string, values: unknown[] = []) {
const client = new Client({ connectionString: e2eDatabaseUrl() });
await client.connect();
try {
return (await client.query(text, values)).rows;
} finally {
await client.end();
}
}
test.describe.serial("the church's brand style and footer", () => {
test.beforeAll(async () => {
const profile = await fetch(`${ACCOUNTS_API}/test/profile`, {
method: "POST",
body: JSON.stringify({
name: "E2E Church",
branding: { style: { fontPairing: "warm", corners: "round" } },
serviceTimes: [{ day: "sunday", time: "09:00", label: "Morning service", campus: null, note: null }],
contact: { email: "office@e2e.test", phone: "+27161234567", whatsapp: null, address: { line1: "1 Church Street", line2: null, suburb: null, city: "Vereeniging", postalCode: "1939" } },
}),
});
expect(profile.ok, await profile.text()).toBe(true);
// Linked to Accounts, as Connect would (the backend reads the profile from this address).
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
await sql(
`INSERT INTO "ProductLink" ("installId", product, url, "publicKey", secret, "connectedAt", "createdAt", "updatedAt") VALUES ($1, 'accounts', $2, 'x', $3, now(), now(), now())`,
[ACCOUNTS_ID, ACCOUNTS_API, encrypt(signing.newLinkSecret())],
);
});
test.afterAll(async () => {
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
});
test("public pages: the church's fonts, round corners and the shared footer, all from this site", async ({ page }) => {
const elsewhere: string[] = [];
page.on("request", (r) => {
if (r.resourceType() === "font" && !r.url().startsWith("http://localhost:3100/")) elsewhere.push(r.url());
});
// The site keeps the profile for a minute; reload until it's there.
await expect(async () => {
await page.goto("/events");
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm", { timeout: 1000 });
}).toPass({ timeout: 90_000 });
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
await expect(page.getByText("E2E Free Evening")).toBeVisible();
const fonts = await page.evaluate(async () => {
await document.fonts.ready;
const h1 = document.querySelector("h1");
return {
body: getComputedStyle(document.body).fontFamily,
heading: h1 ? getComputedStyle(h1).fontFamily : "",
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
loaded: [...document.fonts].filter((f) => f.status === "loaded").map((f) => f.family.replace(/"/g, "")),
};
});
expect(fonts.body).toContain("CC Nunito Sans");
expect(fonts.heading).toContain("CC Fraunces");
expect(fonts.radius).toBe("0.75rem");
expect(fonts.loaded).toContain("CC Nunito Sans");
const footer = page.locator("footer");
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
await expect(footer).toContainText("Sundays 09:00");
await expect(footer).toContainText("1 Church Street");
await expect(footer.getByRole("link", { name: "+27161234567" })).toHaveAttribute("href", "tel:+27161234567");
await expect(footer.getByRole("link", { name: "Your account" })).toHaveAttribute("href", /127\.0\.0\.1/);
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/legal/privacy");
await expect(footer.getByRole("link", { name: "Terms of Use" })).toBeVisible();
await expect(footer.getByRole("button", { name: /cookie/i })).toBeVisible();
await page.goto(`/events/${seed().events.course}`);
await expect(page.getByRole("heading", { name: "E2E Alpha Course" })).toBeVisible();
await expect(page.locator("footer").getByRole("heading", { name: "Service times" })).toBeVisible();
await page.waitForLoadState("networkidle");
const results = await new AxeBuilder({ page }).withTags(TAGS).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
expect(elsewhere).toEqual([]);
});
test("the dashboard keeps its own fonts, corners and footer", async ({ page }) => {
await loginAs(page, "admin");
await page.goto("/dashboard");
await expect(page.locator("[data-cc-staff]").first()).toBeVisible();
await expect(page.locator("main")).toBeVisible();
const look = await page.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
}));
expect(look.body).not.toContain("CC ");
expect(look.radius).toBe("0.5rem");
await expect(page.locator("footer")).toContainText("All rights reserved");
});
});
+16 -1
View File
@@ -5,11 +5,13 @@
* differs from the Events site's (localhost), so their cookies stay apart as on two domains.
*
* Test helpers: POST /test/link { installId, url, secret } links Events, as Connect would;
* GET /test/code?to=<email> answers the last code emailed to that address.
* GET /test/code?to=<email> answers the last code emailed to that address; POST /test/profile changes
* the church profile (3.7.0, church-brand.spec.ts), as an admin's save in Accounts would.
*/
import http from 'node:http';
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
import { createApp } from '../../../accounts/backend/src/app.ts';
import { updateProfile } from '../../../accounts/backend/src/church/profile.ts';
import { createCtx } from '../../../accounts/backend/src/context.ts';
import { loadConfig } from '../../../accounts/backend/src/lib/config.ts';
import { MemoryMessenger } from '../../../accounts/backend/src/lib/messages.ts';
@@ -33,6 +35,19 @@ http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' }).end(messenger.lastCode(to) ?? '');
return;
}
if (req.method === 'POST' && req.url === '/test/profile') {
let body = '';
req.on('data', (c) => { body += c; });
req.on('end', async () => {
try {
const church = await updateProfile(ctx, JSON.parse(body));
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(church));
} catch (e) {
res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ message: (e as Error).message }));
}
});
return;
}
if (req.method === 'POST' && req.url === '/test/link') {
let body = '';
req.on('data', (c) => { body += c; });
+2
View File
@@ -14,6 +14,8 @@ const nextConfig: NextConfig = {
// The end-to-end tests run their own dev server; a separate build folder keeps it
// from clashing with one already running.
distDir: process.env.NEXT_DIST_DIR || ".next",
// The shared fonts and footer (3.7.0) are TypeScript source.
transpilePackages: ["@crosscode/ui"],
images: {
// (images.domains is deprecated in Next 16.)
remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }],
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.6.1",
"version": "3.8.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -12,6 +12,7 @@
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"@dnd-kit/core": "^6.3.1",
"@hookform/resolvers": "^5.2.1",
"@radix-ui/react-accordion": "^1.2.11",
@@ -75,7 +75,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
// Don't render protected content until auth state is known
if (loading || !user) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div data-cc-staff className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="text-sm text-gray-400">Loading…</div>
</div>
);
@@ -88,7 +88,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
// scroll) so the sidebar can be a plain sibling column that never
// scrolls — only the content column (main + footer) scrolls internally.
return (
<div className="h-screen flex flex-col overflow-hidden">
<div data-cc-staff className="h-screen flex flex-col overflow-hidden">
<Navbar />
<LicenceBanner />
<ProviderNotices />
@@ -99,7 +99,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
<Sidebar />
<div className="flex-1 min-w-0 flex flex-col overflow-y-auto">
<main className="flex-1 p-6 bg-gray-50">{children}</main>
<Footer />
<Footer plain />
</div>
</div>
</div>
@@ -107,14 +107,14 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
}
return (
<div className="min-h-screen flex flex-col">
<div data-cc-staff className="min-h-screen flex flex-col">
<Navbar />
<LicenceBanner />
<ProviderNotices />
<PrivacyPrompts />
<CommandPalette />
<main className="flex-1 p-6 bg-gray-50">{children}</main>
<Footer />
<Footer plain />
</div>
);
}
+26 -1
View File
@@ -47,7 +47,8 @@
--input: 214.3 31.8% 91.4%;
--ring: 243 75% 59%;
--radius: 0.5rem;
/* The church's corners (3.7.0, @crosscode/ui fonts.css): soft (0.5rem) unless it picked others. */
--radius: var(--cc-radius-sm, 0.5rem);
/* Fallback brand scale (matches the pre-branding-feature default indigo, brand-600 #4F46E5) */
--brand-50: #EEF2FF;
@@ -73,6 +74,30 @@ html {
scroll-behavior: smooth;
}
/*
* The church's fonts (3.7.0, docs/WEBSITE-1.0-PLAN.md §3 and §9): <html> gets
* data-cc-fonts from its brand style in Accounts, and @crosscode/ui/fonts.css sets these
* variables. Without a pairing they're unset and the page keeps Tailwind's system fonts.
* The dashboard and setup screens (data-cc-staff) stay as they are.
*/
@layer base {
body {
font-family: var(--cc-font-body, theme("fontFamily.sans"));
}
h1,
h2,
h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
html:has([data-cc-staff]) {
--cc-font-body: initial;
--cc-font-heading: initial;
--cc-heading-variation: initial;
--cc-radius-sm: initial;
}
}
/*
* Accessibility (WCAG 2.2 AA, 1.50.0): a clear focus ring for keyboard users on every
* focusable element (mouse clicks don't show it), in the brand colour with a white halo
+10 -2
View File
@@ -1,5 +1,7 @@
import type { Metadata } from "next";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { AuthProvider } from "@/contexts/AuthContext";
import { SiteSettingsProvider } from "@/contexts/SiteSettingsContext";
import { ToastProvider } from "@/components/shared/ToastProvider";
@@ -11,6 +13,8 @@ import { ImpersonationBanner } from "@/components/shared/ImpersonationBanner";
import { SkipLink } from "@/components/layout/SkipLink";
import { resolveToApiOrigin } from "@/lib/api";
import { getServerSettings } from "@/lib/serverSettings";
import { getServerChurch } from "@/lib/serverChurch";
import { ChurchProvider } from "@/contexts/ChurchContext";
import { buildThemeCssVars } from "@/lib/colorScale";
import { appUrl } from "@/lib/siteConfig";
@@ -49,7 +53,7 @@ export async function generateMetadata(): Promise<Metadata> {
}
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const settings = await getServerSettings();
const [settings, church] = await Promise.all([getServerSettings(), getServerChurch()]);
const cssVars = buildThemeCssVars({
primary: settings.primary_color || settings.accent_color,
secondary: settings.secondary_color,
@@ -57,12 +61,15 @@ export default async function RootLayout({ children }: { children: React.ReactNo
});
return (
<html lang="en">
// The church's fonts and corners from Accounts (3.7.0): used by the public pages; the
// dashboard and setup screens keep their own (globals.css, data-cc-staff).
<html lang="en" {...brandAttributes(church?.branding.style)}>
<body>
{cssVars && (
<style id="brand-theme" dangerouslySetInnerHTML={{ __html: `:root{${cssVars}}` }} />
)}
<SkipLink />
<ChurchProvider church={church}>
<SiteSettingsProvider initialSettings={settings}>
<AuthProvider>
<ToastProvider>
@@ -75,6 +82,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
</ToastProvider>
</AuthProvider>
</SiteSettingsProvider>
</ChurchProvider>
</body>
</html>
+1 -1
View File
@@ -247,7 +247,7 @@ export default function SetupPage() {
};
return (
<div className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
<div data-cc-staff className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
<div className={`bg-white rounded-2xl shadow-lg w-full p-8 transition-all ${step === 3 ? "max-w-4xl" : "max-w-lg"}`}>
{/* Heading */}
@@ -1,30 +1,53 @@
"use client";
import Link from "next/link";
import { ChurchFooter } from "@crosscode/ui";
import { appName } from "@/lib/siteConfig";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useChurch } from "@/contexts/ChurchContext";
import { CookieSettingsButton } from "@/components/shared/CookieSettingsButton";
export const Footer = () => {
/**
* The public pages' footer. With the church's Accounts connected (3.7.0) it's the shared church
* footer (as on the Website and Accounts' pages): name and logo, service times, address, contact,
* social links and the church's other sites, with this site's terms and cookie settings below.
* `plain`: the dashboard's own footer, as before.
*/
export const Footer = ({ plain = false }: { plain?: boolean }) => {
const { settings } = useSiteSettings();
const church = useChurch();
const displayName = settings.org_name || appName;
return (
<>
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
<div className="mt-2 space-x-4">
<Link href="/legal/terms" className="hover:underline text-gray-300">
Terms of Use
</Link>
<Link href="/legal/privacy" className="hover:underline text-gray-300">
Privacy Policy
</Link>
<CookieSettingsButton className="hover:underline text-gray-300" />
</div>
</footer>
{church && !plain ? (
<ChurchFooter
church={church}
current="events"
privacyUrl="/legal/privacy"
bottom={
<>
<Link href="/legal/terms" className="hover:underline">Terms of Use</Link>
<CookieSettingsButton className="hover:underline" />
</>
}
/>
) : (
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
<div className="mt-2 space-x-4">
<Link href="/legal/terms" className="hover:underline text-gray-300">
Terms of Use
</Link>
<Link href="/legal/privacy" className="hover:underline text-gray-300">
Privacy Policy
</Link>
<CookieSettingsButton className="hover:underline text-gray-300" />
</div>
</footer>
)}
{/* Spacer so content isn't hidden behind the fixed mobile bottom nav */}
<div className="h-16 md:hidden" aria-hidden="true" />
</>
);
};
};
@@ -9,6 +9,8 @@ import { BottomNav } from "./BottomNav";
import defaultLogo from "@/app/default_logo.png";
import { appName } from "@/lib/siteConfig";
import { resolveToApiOrigin } from "@/lib/api";
import { productLinks } from "@crosscode/ui";
import { useChurch } from "@/contexts/ChurchContext";
type NavLink = {
href: string;
@@ -20,6 +22,10 @@ export const Navbar = () => {
const { user, loading: authLoading, logout } = useAuth();
const { settings, loading: settingsLoading } = useSiteSettings();
const pathname = usePathname();
const church = useChurch();
// The church's other sites from its profile in Accounts (3.7.0): its Website, later its App.
// Not on the dashboard, which stays as it is.
const otherSites = church && !pathname?.startsWith("/dashboard") ? productLinks(church.links, "events") : [];
const displayName = settings.org_name || appName;
const logoSrc = settings.logo_url ? resolveToApiOrigin(settings.logo_url) : null;
@@ -94,6 +100,11 @@ export const Navbar = () => {
{link.label}
</Link>
))}
{otherSites.map(site => (
<a key={site.href} href={site.href} className="text-sm pb-0.5 border-b-2 border-transparent text-gray-700 transition-colors hover:text-brand-600">
{site.label}
</a>
))}
{/* Auth links are only known once the token has been validated —
rendering nothing here (instead of guessing "logged out") avoids
@@ -0,0 +1,13 @@
"use client";
import React, { createContext, useContext } from "react";
import type { Church } from "@crosscode/contracts";
/** The church profile from Accounts (3.7.0), fetched once by the root layout; null without Accounts. */
const ChurchContext = createContext<Church | null>(null);
export function ChurchProvider({ church, children }: { church: Church | null; children: React.ReactNode }) {
return <ChurchContext.Provider value={church}>{children}</ChurchContext.Provider>;
}
export const useChurch = () => useContext(ChurchContext);
@@ -74271,6 +74271,648 @@
}
}
}
},
"/church": {
"get": {
"tags": [
"Site"
],
"summary": "The church's profile",
"description": "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.\n\n**Who:** Anyone.",
"operationId": "getChurch",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"anyOf": [
{
"type": "object",
"properties": {
"schema": {
"type": "string",
"const": "crosscode.church/1"
},
"customerId": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"updatedAt": {
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"shortName": {
"anyOf": [
{
"type": "string",
"maxLength": 30
},
{
"type": "null"
}
]
},
"timezone": {
"type": "string",
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
},
"locale": {
"type": "string",
"pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"
},
"branding": {
"type": "object",
"properties": {
"logoUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"iconUrl": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"colours": {
"type": "object",
"properties": {
"primary": {
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
"accent": {
"anyOf": [
{
"type": "string",
"pattern": "^#[0-9a-fA-F]{6}$"
},
{
"type": "null"
}
]
}
},
"required": [
"primary",
"accent"
],
"additionalProperties": false
},
"style": {
"type": "object",
"properties": {
"fontPairing": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"classic",
"scholarly",
"editorial",
"impact",
"contemporary",
"friendly",
"warm",
"modern"
]
},
{
"type": "null"
}
]
},
"corners": {
"default": null,
"anyOf": [
{
"type": "string",
"enum": [
"sharp",
"soft",
"round"
]
},
{
"type": "null"
}
]
}
},
"required": [
"fontPairing",
"corners"
],
"additionalProperties": false
}
},
"required": [
"logoUrl",
"iconUrl",
"colours"
],
"additionalProperties": false
},
"campuses": {
"maxItems": 50,
"type": "array",
"items": {
"type": "object",
"properties": {
"slug": {
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"slug",
"name",
"address"
],
"additionalProperties": false
}
},
"serviceTimes": {
"maxItems": 100,
"type": "array",
"items": {
"type": "object",
"properties": {
"day": {
"type": "string",
"enum": [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
]
},
"time": {
"type": "string",
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"
},
"label": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"campus": {
"anyOf": [
{
"type": "string",
"maxLength": 100,
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
},
{
"type": "null"
}
]
},
"note": {
"anyOf": [
{
"type": "string",
"maxLength": 300
},
{
"type": "null"
}
]
}
},
"required": [
"day",
"time",
"label",
"campus",
"note"
],
"additionalProperties": false
}
},
"contact": {
"type": "object",
"properties": {
"email": {
"anyOf": [
{
"type": "string",
"maxLength": 254,
"format": "email",
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
},
{
"type": "null"
}
]
},
"phone": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"whatsapp": {
"anyOf": [
{
"type": "string",
"pattern": "^\\+[1-9]\\d{6,14}$"
},
{
"type": "null"
}
]
},
"address": {
"anyOf": [
{
"type": "object",
"properties": {
"line1": {
"type": "string",
"minLength": 1,
"maxLength": 200
},
"line2": {
"anyOf": [
{
"type": "string",
"maxLength": 200
},
{
"type": "null"
}
]
},
"suburb": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"city": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"province": {
"anyOf": [
{
"type": "string",
"maxLength": 100
},
{
"type": "null"
}
]
},
"postalCode": {
"anyOf": [
{
"type": "string",
"maxLength": 20
},
{
"type": "null"
}
]
},
"country": {
"type": "string",
"pattern": "^[A-Z]{2}$"
},
"geo": {
"anyOf": [
{
"type": "object",
"properties": {
"lat": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"lng": {
"type": "number",
"minimum": -180,
"maximum": 180
}
},
"required": [
"lat",
"lng"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"line1",
"line2",
"suburb",
"city",
"province",
"postalCode",
"country",
"geo"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"email",
"phone",
"whatsapp",
"address"
],
"additionalProperties": false
},
"social": {
"maxItems": 20,
"type": "array",
"items": {
"type": "object",
"properties": {
"network": {
"type": "string",
"enum": [
"facebook",
"instagram",
"youtube",
"tiktok",
"x",
"spotify",
"whatsapp-channel",
"other"
]
},
"url": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"network",
"url"
],
"additionalProperties": false
}
},
"links": {
"type": "object",
"properties": {
"website": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"events": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"app": {
"anyOf": [
{
"type": "string",
"maxLength": 2048,
"format": "uri"
},
{
"type": "null"
}
]
},
"accounts": {
"type": "string",
"maxLength": 2048,
"format": "uri"
}
},
"required": [
"website",
"events",
"app",
"accounts"
],
"additionalProperties": false
}
},
"required": [
"schema",
"customerId",
"updatedAt",
"name",
"shortName",
"timezone",
"locale",
"branding",
"campuses",
"serviceTimes",
"contact",
"social",
"links"
],
"additionalProperties": false
},
{
"type": "null"
}
]
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
}
}
}
}
},
"components": {
+125
View File
@@ -7760,6 +7760,28 @@ export interface paths {
patch?: never;
trace?: never;
};
"/church": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The church's profile
* @description The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.
*
* **Who:** Anyone.
*/
get: operations["getChurch"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -40739,4 +40761,107 @@ export interface operations {
};
};
};
getChurch: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
schema: "crosscode.church/1";
/** Format: uuid */
customerId: string;
/** Format: date-time */
updatedAt: string;
name: string;
shortName: string | null;
timezone: string;
locale: string;
branding: {
logoUrl: string | null;
iconUrl: string | null;
colours: {
primary: string;
accent: string | null;
};
style?: {
/** @default null */
fontPairing: ("classic" | "scholarly" | "editorial" | "impact" | "contemporary" | "friendly" | "warm" | "modern") | null;
/** @default null */
corners: ("sharp" | "soft" | "round") | null;
};
};
campuses: {
slug: string;
name: string;
address: {
line1: string;
line2: string | null;
suburb: string | null;
city: string;
province: string | null;
postalCode: string | null;
country: string;
geo: {
lat: number;
lng: number;
} | null;
} | null;
}[];
serviceTimes: {
/** @enum {string} */
day: "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
time: string;
label: string | null;
campus: string | null;
note: string | null;
}[];
contact: {
email: string | null;
phone: string | null;
whatsapp: string | null;
address: {
line1: string;
line2: string | null;
suburb: string | null;
city: string;
province: string | null;
postalCode: string | null;
country: string;
geo: {
lat: number;
lng: number;
} | null;
} | null;
};
social: {
/** @enum {string} */
network: "facebook" | "instagram" | "youtube" | "tiktok" | "x" | "spotify" | "whatsapp-channel" | "other";
/** Format: uri */
url: string;
}[];
links: {
website: string | null;
events: string | null;
app: string | null;
/** Format: uri */
accounts: string;
};
} | null;
};
};
};
};
};
}
@@ -0,0 +1,19 @@
import type { Church } from "@crosscode/contracts";
import { API_BASE } from "@/lib/api";
/**
* The church profile from the church's Accounts (3.7.0), through the backend's
* `GET /api/v2/church`: the brand style for `<html>` and the shared footer. null when Accounts
* isn't connected or the backend can't be reached, and the pages look as they always have.
* Fetched the same way as getServerSettings, so Next dedupes it within a request.
*/
export async function getServerChurch(): Promise<Church | null> {
if (!API_BASE) return null;
try {
const res = await fetch(`${API_BASE}/api/v2/church`, { next: { revalidate: 60 } });
if (!res.ok) return null;
return ((await res.json())?.data as Church | null) ?? null;
} catch {
return null;
}
}
+4
View File
@@ -2,6 +2,8 @@
module.exports = {
content: [
"./src/**/*.{js,ts,jsx,tsx}",
// The shared footer (3.7.0)
"../../../packages/ui/src/**/*.{ts,tsx}",
],
theme: {
extend: {
@@ -47,6 +49,8 @@ module.exports = {
// colorScale.ts's buildBrandScale + globals.css for the static
// fallback defaults used when no setting is saved yet).
brand: {
// `brand` alone (the shared footer's links, @crosscode/ui)
DEFAULT: "var(--brand-700)",
50: "var(--brand-50)",
100: "var(--brand-100)",
200: "var(--brand-200)",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.6.1",
"version": "3.7.2",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",

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