Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0dd1284ee8 | ||
|
|
d0eff65e6d | ||
|
|
799c193fe1 | ||
|
|
f651ae2530 | ||
|
|
bb36e06fa4 | ||
|
|
74dee881e4 | ||
|
|
969d0110a1 | ||
|
|
fd097d8446 | ||
|
|
9cf2956aff | ||
|
|
986d69d51d | ||
|
|
d3789f9b30 | ||
|
|
ce169851f7 | ||
|
|
0b518761b7 | ||
|
|
a5e3a6bb6c | ||
|
|
2e8e4c04ca | ||
|
|
7391f97cfa | ||
|
|
c8e270dbf1 | ||
|
|
b2a163bb39 | ||
|
|
2eef8d1da3 | ||
|
|
dfd7278f7b | ||
|
|
aacfd228a6 | ||
|
|
e32d9ecb09 | ||
|
|
49153e6f07 | ||
|
|
5b9dc559b6 | ||
|
|
ad488c3280 | ||
|
|
50ac7fab33 | ||
|
|
7032e16894 | ||
|
|
b720706143 | ||
|
|
5380a87be1 | ||
|
|
bd472ddc05 | ||
|
|
c22d7ecad6 | ||
|
|
514a6d8bc0 | ||
|
|
8372ef8c6b | ||
|
|
250c631fb4 | ||
|
|
753e2c4631 | ||
|
|
42684ed727 | ||
|
|
1e3004189a | ||
|
|
0c521ff614 | ||
|
|
4897489fb1 | ||
|
|
1c69b0cce9 | ||
|
|
b3318941ae | ||
|
|
2efafa166e | ||
|
|
e0c82fe314 | ||
|
|
a474cdcda6 | ||
|
|
8234bb3bc1 | ||
|
|
dd86021302 |
+149
@@ -2,6 +2,155 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## contracts@1.24.0 - 2026-11-30
|
||||
|
||||
Cross Code's devotionals two years ahead, and Apps fetch 2 weeks (Joshua, 2026-11-30). Additive.
|
||||
|
||||
- `CROSSCODE_DEVOTIONALS_SCHEDULE_MONTHS` (24): how far ahead the Hub schedules them.
|
||||
- `CROSSCODE_DEVOTIONALS_FETCH_DAYS` (14): the most days one `GET /api/v2/devotionals` answer
|
||||
covers, `from` included. `CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3) is kept but deprecated.
|
||||
- The devotionals CSV takes 800 rows and 8 MB (was 400 and 2 MB), so two years fit in one file; a
|
||||
date past `latestDate` says "too far ahead (the last day is …)" instead of naming 3 months.
|
||||
- Checked: contracts' tests (341), typecheck.
|
||||
|
||||
## agent@1.7.0 + contracts@1.23.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in the server agent (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
|
||||
- **Contracts 1.23.0:** the `seed-scenario` job (`church`, `scenario`, optional `adminEmail`; 45
|
||||
minutes): a whole demo scenario in one job, on whatever the church has installed.
|
||||
`SEED_SCENARIO_JOB_MIN_AGENT` (1.7.0). Additive.
|
||||
- **Agent 1.7.0:** `seed-scenario` → `crosscode demo <church> --scenario <s>`; `seed-demo` for `accounts` and `app` (`crosscode demo <church> <product> …`),
|
||||
and `scenario` passed on as `--scenario` for every product (contracts `SEED_SCENARIO_MIN_AGENT`,
|
||||
`SEED_APP_DEMO_MIN_AGENT`). Events' jobs keep their old form (no product).
|
||||
- **crosscode script:** `crosscode demo <church> --scenario <s>` (no product, no profile) loads the
|
||||
scenario on every product the church has here, in deploy order, skipping the others; checks
|
||||
every installed release against the scenario minimums first; each product takes its own
|
||||
backup; the first failure stops the rest and names what's out of step (`loaded`, `skipped` in
|
||||
the report). Events' demo is now `cmd_demo_events`. `crosscode demo <church> app …` says the
|
||||
App's demo comes with App 1.0.0, instead of misreading `app` as a second church.
|
||||
|
||||
## website@1.8.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in the Church Website (docs/APP-1.0-PLAN.md §12, "Demo scenarios"). No
|
||||
migration. Details in `apps/website/CHANGELOG.md`.
|
||||
|
||||
- **Website 1.8.0:** `npm run demo -- --profile <p> --scenario <p>` loads a profile as part of its
|
||||
demo scenario: the leaders are the scenario's people (`@crosscode/demo`), the pastor the home
|
||||
page's and the messages' speaker; with a linked Cross Events, Events' events show through the
|
||||
feed (Show events from, fetched at once) instead of the profile's own.
|
||||
- **crosscode script:** `crosscode demo <church> website … --scenario <p>` passes it on and refuses a
|
||||
Website before 1.8.0; the Website installs and builds `packages/demo`.
|
||||
|
||||
## contracts@1.22.0 - 2026-11-30
|
||||
|
||||
Bible translations for the Church App's devotionals (docs/BIBLE-PERMISSIONS.md, APP-1.0-PLAN.md §6
|
||||
and decision 14). Additive except for the notice texts and one translation's name; no id changes,
|
||||
nothing has shown them yet.
|
||||
|
||||
- **Only free translations in 1.0:** each translation has a `licence` ("public-domain" or
|
||||
"permission"); `FREE_BIBLE_TRANSLATION_IDS` (KJV, BSB) is what the Hub and the App offer, and
|
||||
`checkDevotionalCsv(text, { translations })` refuses any other, naming the publisher to ask.
|
||||
- **The Berean Standard Bible (`BSB`)**, public domain since 2023, YouVersion 3034. The CSV template
|
||||
and the devotionals sample now quote the BSB and the KJV.
|
||||
- **Notices corrected** to each publisher's current wording: NLT (Tyndale House Ministries), ESV
|
||||
(ESV Text Edition: 2025, the Creative Commons and translation clauses), AFR53 and AFR83 (the
|
||||
Bible Society's digital short form). The NIV and NKJV notices were already right.
|
||||
- **`AFR83` is named "Afrikaans 1983/1992-vertaling"**, as the Bible Society names it.
|
||||
- **New per translation:** `acknowledgement` (the full notice, for the App's Acknowledgements
|
||||
page), `disclaimer` (the Bible Society's, required with its translations next to content it
|
||||
hasn't approved; null for the others), `publisher` and `permissionsUrl` (null for the KJV).
|
||||
- **`FREE_QUOTE_VERSES`** (500) and **`quotedVerses(passages)`**: verses quoted per translation,
|
||||
so the Hub and the App can warn before the free allowance runs out. `devotionalDisclaimer`.
|
||||
|
||||
## events@3.8.0 + @crosscode/demo 1.1.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Cross Events (docs/APP-1.0-PLAN.md §8 and §12). One migration.
|
||||
Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
- **Events 3.8.0:** STOP stops all WhatsApp (not only news), checked before every message, kept by
|
||||
number and per account (`whatsapp_opted_out` from Accounts), passed on to Accounts
|
||||
(`whatsapp.optout`); START turns it back on without Accounts. The eight demo scenarios
|
||||
(`set-demo.js --profile=<scenario>`), built around the scenario's own people and campuses.
|
||||
- **`@crosscode/demo` 1.1.0:** each person's `gender` (for Events' gendered events and cabins).
|
||||
- **crosscode script:** Events takes the scenarios as demo profiles; Events installs and builds
|
||||
`packages/demo`.
|
||||
|
||||
## accounts@1.9.0 + @crosscode/demo 1.0.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Accounts (docs/APP-1.0-PLAN.md §8 and §12). One migration. Details
|
||||
in `apps/accounts/CHANGELOG.md`.
|
||||
|
||||
- **Accounts 1.9.0:** `messaging.get` and the `messaging.changed` hint (the App sends with the
|
||||
church's one set of email and WhatsApp settings); the WhatsApp opt-out for every product
|
||||
(`whatsapp.optout`, its own WAWP webhook for a church without Events, `whatsapp_opted_out` in
|
||||
`user.updated`, "Turn WhatsApp back on" on the account page); a demo scenario's church profile,
|
||||
logo, icon and people (`npm run demo -- --profile <scenario> --force`).
|
||||
- **`@crosscode/demo` 1.0.0** (new, `packages/demo`, not tagged): the eight scenarios' churches,
|
||||
people (same `sub` in every product) and SVG logos, for every product's demo loader.
|
||||
- **crosscode script:** `crosscode demo <church> accounts --profile <scenario>` (backup, load,
|
||||
reload); `--scenario <s>` on every demo (the profile must be the scenario's); Accounts installs
|
||||
and builds `packages/demo`.
|
||||
|
||||
## contracts@1.21.0 - 2026-11-30
|
||||
|
||||
Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the
|
||||
Hub loads every product with the same church. Additive for `seed-demo` jobs older Hubs send.
|
||||
|
||||
- **`agent.DEMO_SCENARIOS`**: eight, one per Website demo profile and keyed by it, each its own
|
||||
fictional church (St Columba's, Grace Cathedral, Ignite Church, Harbour City, Acacia Hill, Karoo
|
||||
Gemeenskapskerk, Northpoint, Riverside) with a label, description, campuses, language, the App's
|
||||
active-member band, and the profile each product loads. `demoScenario(key)`,
|
||||
`DEMO_SCENARIO_ORDER` (Accounts, Events, Website, App), `DEMO_SCENARIO_MIN_VERSIONS` (Accounts
|
||||
1.9.0, Events 3.8.0, Website 1.8.0, App 1.0.0).
|
||||
- **`seed-demo`** takes an optional `scenario`; its `profile` must then be the scenario's for the
|
||||
product. `accounts` joins `DEMO_PRODUCTS` (the scenario's church profile, logo, icon and people;
|
||||
no `adminEmail`). Events gets a profile per scenario next to its four (`EVENTS_DEMO_PROFILES`),
|
||||
so a scenario name with no `product` is an Events demo.
|
||||
- **`APP_DEMO_PROFILES`** is the eight scenarios. 1.20.0's `acacia-hill` is gone: it's the
|
||||
`community-family` scenario, and no App or Hub had used it.
|
||||
- `SEED_SCENARIO_MIN_AGENT` (1.7.0) and `SEED_DEMO_MIN_AGENT_BY_PRODUCT`. JSON Schema `agent-job`
|
||||
regenerated.
|
||||
|
||||
## contracts@1.20.0 - 2026-11-30
|
||||
|
||||
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12), the first step of phase 6. Additive:
|
||||
products on 1.19.0 keep working. Accounts refuses the two new requests (`INVALID_REQUEST`) until
|
||||
Accounts 1.9.0 answers them.
|
||||
|
||||
- **`crosscode.devotional/1`** (`src/devotional.ts`): `devotionalSchema` (date, title, the passage
|
||||
with its text and translation, body, prayer, author, `source` `crosscode` or `church`),
|
||||
`devotionalsReplySchema` (the Hub's `GET /api/v2/devotionals?from=`, Cross Code's only),
|
||||
`CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3). **CSV import** shared by the Hub and the App:
|
||||
`DEVOTIONAL_CSV_COLUMNS`, `parseCsv` (quotes, line breaks, BOM, `;` files), `checkDevotionalCsv`
|
||||
(each row's errors by column, warnings, days already taken, a `latestDate` limit, dates twice in
|
||||
the file), `devotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`.
|
||||
- **Bible passages** (`src/bible.ts`): `BIBLE_TRANSLATIONS` (NLT, ESV, NIV, NKJV, KJV, AFR53, AFR83,
|
||||
each with its YouVersion id and copyright line), `BIBLE_BOOKS` (USFM codes, English and Afrikaans
|
||||
names, abbreviations, chapters), `parseBibleReference` ("Johannes 3:16–18", "1 Kor. 13:4-7",
|
||||
"Rom 8:38-9:1", "Jude 3"), `formatBibleReference`, `passageVerseCount`, `youVersionUrl`,
|
||||
`PASSAGE_WARN_VERSES` (25).
|
||||
- **Identity requests:** `messaging.get` (the church's SMTP and WAWP settings for the App, secrets
|
||||
sealed with the link's secret; `messagingGetReplySchema`) and the `messaging.changed` hint
|
||||
Accounts sends back (`MESSAGING_CHANGED_PATH`); `whatsapp.optout` (a STOP received by any
|
||||
product; `whatsappOptOutReplySchema`). `whatsapp_opted_out` (optional) in the profile that
|
||||
`user.updated` and the sign-in claims carry.
|
||||
- **App:** `APP_MODULES`; `hub.DEVOTIONALS_PATH` and its error codes; `agent.APP_DEMO_PROFILES`
|
||||
(`acacia-hill`), `app` in `DEMO_PRODUCTS`, `SEED_APP_DEMO_MIN_AGENT` (1.7.0, not released yet).
|
||||
- **Church export:** the `app` section (`exportAppSchema`: prayer wall rules, commitments as rules
|
||||
with their skips, "I prayed" marks, campaigns, testimonies, prayer requests with their
|
||||
moderation, emergency numbers, announcements, the church's own devotionals, simple events), and
|
||||
`people[].roles` (optional) for a person with several roles.
|
||||
- New samples: `devotionals-reply`, `messaging-get`, `messaging-get-reply`, `messaging-changed`,
|
||||
`whatsapp-optout`, `whatsapp-optout-reply`, `church-export-app`. New JSON Schemas: `devotional`,
|
||||
`devotionals-reply`, `messaging-get-reply`, `messaging-changed`, `whatsapp-optout-reply`.
|
||||
|
||||
## website@1.7.1 - 2026-11-28
|
||||
|
||||
Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only).
|
||||
One migration: a nullable `framing` column on `Ministry`, `Leader` and `SimpleEvent`. Details in
|
||||
`apps/website/CHANGELOG.md`.
|
||||
|
||||
## website@1.7.0 - 2026-11-27
|
||||
|
||||
Photos can be moved and zoomed in their frame, and unused photos deleted. Details in
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
# Cross Code platform
|
||||
|
||||
The monorepo for the Cross Code products that come after Cross Events, and the formats they share.
|
||||
The plan for every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where
|
||||
things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
|
||||
The monorepo for every Cross Code product except the Hub, and the formats they share. The plan for
|
||||
every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where things
|
||||
stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md), and the latest release of everything in
|
||||
[`docs/VERSIONS.md`](./docs/VERSIONS.md).
|
||||
|
||||
| Folder | What | Status |
|
||||
|--------|------|--------|
|
||||
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including Cross Events and the Hub | Phase 0, in progress |
|
||||
| `packages/ui` | `@crosscode/ui`: shared UI for the Website, App and Accounts | Placeholder, filled in during the Website phase |
|
||||
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect) | Placeholder (phase 3) |
|
||||
| `apps/website` | Church Website | Placeholder (phase 5) |
|
||||
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
|
||||
| `apps/events` | Cross Events (moved in from `joshua/hope-events` in 2.2.0) | Released and in use |
|
||||
| `apps/accounts` | Accounts: the per-church sign-in (OpenID Connect), the church profile | Released and in use |
|
||||
| `apps/website` | Church Website | Released and in use (phase 5) |
|
||||
| `apps/app` | Church App (PWA, House of Prayer) | Placeholder, being built (phase 6, [`docs/APP-1.0-PLAN.md`](./docs/APP-1.0-PLAN.md)) |
|
||||
| `apps/agent` | The server agent: runs the Hub's signed jobs through the `crosscode` script | Released and in use |
|
||||
| `packages/contracts` | `@crosscode/contracts`: the shared JSON formats (zod schemas, JSON Schema, TypeScript types, sample payloads) used by every product, including the Hub | Released and in use |
|
||||
| `packages/auth-client` | `@crosscode/auth-client`: how a product signs in through Accounts | In use |
|
||||
| `packages/seo` | `@crosscode/seo`: JSON-LD and meta for every public site | In use |
|
||||
| `packages/ui` | `@crosscode/ui`: fonts, brand style, `ChurchFooter` | In use |
|
||||
| `packages/demo` | `@crosscode/demo`: the demo scenarios' churches, people and logos | In use (Accounts, Events, the Website) |
|
||||
| `scripts/` | The `crosscode` script: install, deploy, demo, env, export, uninstall on the servers | In use (`main` is the release) |
|
||||
|
||||
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
|
||||
([`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md)). Cross Code Hub (`joshua/events-hub`) stays in
|
||||
its own repo and gets `@crosscode/contracts` as a packed release committed there (decision 22).
|
||||
Cross Code Hub (`joshua/events-hub`) stays in its own repo and gets `@crosscode/contracts` as a
|
||||
packed release committed there (decision 22).
|
||||
|
||||
## Docs
|
||||
|
||||
@@ -22,8 +28,11 @@ its own repo and gets `@crosscode/contracts` as a packed release committed there
|
||||
|------|------|
|
||||
| [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) | The plan: products, contracts, Accounts, sync, Hub, servers, build order, pricing, decisions |
|
||||
| [`docs/HANDOVER.md`](./docs/HANDOVER.md) | Where each phase stands and what's next |
|
||||
| [`docs/VERSIONS.md`](./docs/VERSIONS.md) | The latest release of everything, and what's deployed where |
|
||||
| [`docs/hub-protocol.md`](./docs/hub-protocol.md) | Install ↔ Hub protocol, versions 1 and 2 (a copy lives in `events-hub`) |
|
||||
| [`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md) | Phase 1b: Cross Events into the monorepo, the `crosscode` script |
|
||||
| `docs/*-PLAN.md` | Each phase's plan and decisions (Events 2.2, 2.4, 3.0; Accounts 1.0; Agent 1.0; Website 1.0; App 1.0) |
|
||||
| [`docs/ROLLOUT-1.0.md`](./docs/ROLLOUT-1.0.md) | The rollout checklist |
|
||||
| [`docs/BIBLE-PERMISSIONS.md`](./docs/BIBLE-PERMISSIONS.md) | The Bible publishers' terms for the Church App's devotionals, the permission requests and their status |
|
||||
|
||||
## Rules (ROADMAP-v3 §1)
|
||||
|
||||
|
||||
@@ -1,5 +1,57 @@
|
||||
# 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
|
||||
|
||||
@@ -16,6 +16,10 @@ sign-in settings, linked products and the church profile here.
|
||||
- Roles stay in each product: Accounts only knows who someone is (plan §2, "Roles stay in each
|
||||
product").
|
||||
- Products sign in with `@crosscode/auth-client` (packages/auth-client).
|
||||
- 1.9.0: the church's one set of email and WhatsApp settings for the App (`messaging.get`,
|
||||
`messaging.changed`); the WhatsApp opt-out for every product (`src/accounts/whatsapp.ts`, its own
|
||||
WAWP webhook in `src/links/whatsappWebhook.ts`); demo scenarios (`npm run demo -- --profile
|
||||
<scenario> --force`, `src/demo/scenario.ts`, with `@crosscode/demo`; demo sites only).
|
||||
|
||||
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `ACCOUNTS_URL=http://localhost:3200`,
|
||||
`LINKS_ALLOW_PRIVATE=true`), `npx prisma migrate deploy`, then `npm run dev` in both folders (the
|
||||
|
||||
@@ -3,6 +3,17 @@
|
||||
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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.8.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")
|
||||
);
|
||||
@@ -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())
|
||||
|
||||
@@ -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,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);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* /api/self/… the account page's own sign-in
|
||||
* /api/church/v1, /api/links/v1/… for the church's other products
|
||||
* /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0)
|
||||
* /api/v2/webhooks/whatsapp WAWP's webhook: STOP replies (1.9.0)
|
||||
* /api/v2/… the pages' API (sign-in steps, account, admin, setup)
|
||||
*/
|
||||
import express from 'express';
|
||||
@@ -19,6 +20,7 @@ import { meRouter } from './me/routes.js';
|
||||
import { LOGOUT_JS } from './oidc/pages.js';
|
||||
import { publicRouter } from './public/routes.js';
|
||||
import { requestsRouter } from './links/requests.js';
|
||||
import { whatsappWebhookRouter } from './links/whatsappWebhook.js';
|
||||
import { setupRouter } from './setup/routes.js';
|
||||
import { health } from './hub/client.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
@@ -50,6 +52,8 @@ export function createApp(ctx: Ctx, provider: Provider) {
|
||||
app.use('/api/self', selfRouter(ctx));
|
||||
app.use('/api', requestsRouter(ctx, provider));
|
||||
app.use('/api', publicRouter(ctx));
|
||||
// 1.9.0: WAWP's webhook (STOP replies), before the pages' API: no same-origin check, its own secret.
|
||||
app.use(whatsappWebhookRouter(ctx));
|
||||
|
||||
const v2 = express.Router();
|
||||
v2.use(express.json({ limit: '64kb' }));
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md §12, "Demo scenarios"): the
|
||||
* scenario's church becomes the church profile (its own name, logo, icon, colours, campuses,
|
||||
* service times and contact details), and its people get accounts. Loaded first, so Cross Events,
|
||||
* the Website and the App then build their demo data around the same church and people.
|
||||
*
|
||||
* Only for demo sites (`crosscode demo <church> accounts --profile <scenario>`, which takes a backup
|
||||
* first). People keep the same account id on every load (`demoId`), so products' copies still match.
|
||||
* Demo people from before who aren't in this scenario are anonymised; real people (any address not at
|
||||
* example.com) and Accounts admins are never touched.
|
||||
*/
|
||||
import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts';
|
||||
import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { hashPassword } from '../lib/passwords.js';
|
||||
import { updateProfile } from '../church/profile.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
|
||||
/** Where Accounts serves the scenario's logo and icon (`/api/demo-assets/<scenario>/logo.svg`). */
|
||||
export const DEMO_ASSETS_PATH = '/api/demo-assets';
|
||||
const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const;
|
||||
|
||||
/** The SVG for a demo asset, or null for anything else. */
|
||||
export function demoAsset(scenario: string, file: string): string | null {
|
||||
const key = agent.demoScenarioSchema.safeParse(scenario);
|
||||
const draw = (DEMO_ASSET_FILES as Record<string, (s: agent.DemoScenarioKey) => string>)[file];
|
||||
return key.success && draw ? draw(key.data) : null;
|
||||
}
|
||||
|
||||
export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number }
|
||||
|
||||
const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
const CHUNK = 500;
|
||||
|
||||
export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise<ScenarioResult> {
|
||||
const { profile } = demoChurch(scenario);
|
||||
const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`;
|
||||
|
||||
// The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed).
|
||||
await updateProfile(ctx, {
|
||||
name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale,
|
||||
branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style },
|
||||
campuses: profile.campuses, serviceTimes: profile.serviceTimes,
|
||||
contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social,
|
||||
});
|
||||
|
||||
// The people.
|
||||
const people = demoPeople(scenario);
|
||||
const wanted = new Set(people.map((p) => p.id));
|
||||
const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a]));
|
||||
let removed = 0;
|
||||
for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) {
|
||||
if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue;
|
||||
await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } });
|
||||
await anonymise(ctx, a.id);
|
||||
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
|
||||
removed++;
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(DEMO_PASSWORD);
|
||||
const notice = await currentNoticeVersion(ctx);
|
||||
const now = ctx.now();
|
||||
const fields = (p: (typeof people)[number]) => ({
|
||||
name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true,
|
||||
phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const,
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now,
|
||||
noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null,
|
||||
whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
});
|
||||
let updated = 0;
|
||||
// Already here (this scenario loaded before, or anonymised when another was): brought back as they were.
|
||||
for (const p of people) {
|
||||
const a = existing.get(p.id);
|
||||
if (!a) continue;
|
||||
// Never take over a real person's account, nor an admin's.
|
||||
if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue;
|
||||
const other = await ctx.db.account.findUnique({ where: { email: p.email } });
|
||||
if (other && other.id !== p.id) continue;
|
||||
await ctx.db.account.update({ where: { id: p.id }, data: fields(p) });
|
||||
updated++;
|
||||
}
|
||||
// New: in chunks, as the larger scenarios have a couple of thousand people.
|
||||
const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email));
|
||||
const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email));
|
||||
for (let i = 0; i < fresh.length; i += CHUNK) {
|
||||
await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) });
|
||||
}
|
||||
|
||||
await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } });
|
||||
await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() }));
|
||||
return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed };
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { loginEvent } from '../lib/audit.js';
|
||||
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
import { applyKnownOptOut } from '../accounts/whatsapp.js';
|
||||
|
||||
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
|
||||
|
||||
@@ -115,7 +116,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
|
||||
}
|
||||
if (stage === 'setup_two_factor') {
|
||||
// Only the ways that can deliver a code now (1.2.0): an app always works.
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone && !a.whatsappOptedOut ? ['whatsapp'] : [])];
|
||||
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||
}
|
||||
if (stage === 'notice') {
|
||||
@@ -177,6 +178,7 @@ export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<str
|
||||
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
|
||||
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
|
||||
await loginEvent(ctx, a.id, 'account_created');
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** Encrypted at rest; never sent to the browser. */
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks', 'wawp_webhook_secret']);
|
||||
|
||||
/** The settings an admin may read and change through the generic settings API. */
|
||||
export const ADMIN_SETTINGS = new Set([
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, `church.changed` and (1.9.0) `messaging.changed`. Each is a
|
||||
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
|
||||
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
|
||||
* export).
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS, MESSAGING_CHANGED_PATH } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { callSibling, siblingUrl } from './http.js';
|
||||
@@ -14,7 +14,10 @@ import { callSibling, siblingUrl } from './http.js';
|
||||
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
|
||||
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
|
||||
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed' | 'messaging.changed';
|
||||
|
||||
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
|
||||
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
|
||||
|
||||
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
|
||||
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
|
||||
@@ -23,7 +26,7 @@ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: str
|
||||
for (const link of links) {
|
||||
const callId = crypto.randomUUID();
|
||||
made.push(await ctx.db.delivery.create({
|
||||
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
data: { linkId: link.installId, callId, type, path: PATHS[type] ?? ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
}));
|
||||
}
|
||||
return made;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 4): one set of email and WhatsApp settings per church,
|
||||
* kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the
|
||||
* Church App) are sent `messaging.changed` when they change, so they fetch them again.
|
||||
*/
|
||||
import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { queueCall } from './deliveries.js';
|
||||
|
||||
/** The settings that make up the church's email and WhatsApp. */
|
||||
const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']);
|
||||
const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']);
|
||||
|
||||
/** Which parts the changed setting keys touch. */
|
||||
export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } {
|
||||
return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the change and tells every product that asked for the settings, except the one that
|
||||
* made the change (`exceptLinkId`, e.g. Events saving its own into Accounts).
|
||||
*/
|
||||
export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) {
|
||||
if (!parts.email && !parts.whatsapp) return;
|
||||
const at = ctx.now().toISOString();
|
||||
await ctx.settings.set('messaging_updated_at', at);
|
||||
const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } });
|
||||
const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId);
|
||||
if (!linkIds.length) return;
|
||||
await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds });
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
|
||||
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
} from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import { LINK_HEADERS, openLinkValue, sealLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { ProductLink } from '../generated/prisma/client.js';
|
||||
import { limit } from '../http.js';
|
||||
@@ -32,6 +32,8 @@ import { turnOff } from '../accounts/twoFactor.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
|
||||
import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js';
|
||||
import { messagingChanged } from './messaging.js';
|
||||
|
||||
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
|
||||
const PROFILE_EDITORS = new Set(['website']);
|
||||
@@ -134,6 +136,7 @@ async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportP
|
||||
for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } });
|
||||
await knows(ctx, link.installId, a.id, 'import', { upgrade: true });
|
||||
await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } });
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
}
|
||||
return { id: p.id, outcome: 'created', sub: p.id, reason: null };
|
||||
}
|
||||
@@ -225,6 +228,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
}
|
||||
const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } });
|
||||
await knows(ctx, link.installId, a.id, 'ensure');
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
const token = randomToken();
|
||||
// Only the product's own address: never somewhere else.
|
||||
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
|
||||
@@ -259,7 +263,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
if (Object.keys(data).length) {
|
||||
await ctx.db.account.update({ where: { id: a.id }, data });
|
||||
if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } });
|
||||
await profileChanged(ctx, a.id);
|
||||
if (!(data.phone && (await applyKnownOptOut(ctx, a.id)))) await profileChanged(ctx, a.id);
|
||||
}
|
||||
await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) });
|
||||
return reply({ ok: true as const });
|
||||
@@ -323,6 +327,20 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
|
||||
return reply({ people });
|
||||
}
|
||||
case 'messaging.get': {
|
||||
// 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings,
|
||||
// secrets sealed with the link's secret. The product is sent messaging.changed from now on.
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } });
|
||||
const out = await messagingSettings(ctx, secret);
|
||||
await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp });
|
||||
return reply(out);
|
||||
}
|
||||
case 'whatsapp.optout': {
|
||||
// 1.9.0 (decision 11): a STOP the product received. Kept here for every product.
|
||||
const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) });
|
||||
await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts });
|
||||
return reply({ accounts });
|
||||
}
|
||||
case 'church.update': {
|
||||
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
|
||||
// checks it's the Website, that the person signs in through it, and audits it as theirs.
|
||||
@@ -382,6 +400,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
if (save && (email?.saved || whatsapp?.saved)) await messagingChanged(ctx, { email: !!email?.saved, whatsapp: !!whatsapp?.saved }, link.installId);
|
||||
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
|
||||
const status = await messagingStatus(ctx);
|
||||
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
|
||||
@@ -419,7 +438,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
const out = await handle(ctx, provider, link, secret, request, req);
|
||||
// Checks write nothing, so they needn't be remembered.
|
||||
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
|
||||
// messaging.get (1.9.0) carries sealed secrets: never kept either.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check' || request.type === 'messaging.get';
|
||||
if (!isCheck) {
|
||||
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
|
||||
}
|
||||
@@ -465,6 +485,29 @@ async function messagingStatus(ctx: Ctx) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* messaging.get (1.9.0): what Accounts sends with (its saved settings, else the server's .env),
|
||||
* the password and token sealed with the link's secret. A part that isn't set up is null.
|
||||
*/
|
||||
async function messagingSettings(ctx: Ctx, secret: string) {
|
||||
const s = ctx.settings;
|
||||
const host = (await s.get('smtp_host')) || ctx.config.smtp?.host || null;
|
||||
const port = Number((await s.get('smtp_port')) || ctx.config.smtp?.port || 587);
|
||||
const pass = (await s.get('smtp_pass')) || ctx.config.smtp?.pass || '';
|
||||
const from = (await s.get('smtp_from')) || ctx.config.smtp?.from || '';
|
||||
const email = host && from ? {
|
||||
host, port,
|
||||
secure: (await s.get('smtp_secure')) === 'true' || (ctx.config.smtp?.secure ?? port === 465),
|
||||
user: (await s.get('smtp_user')) || ctx.config.smtp?.user || '',
|
||||
pass: pass ? sealLinkValue(secret, pass) : null,
|
||||
from,
|
||||
} : null;
|
||||
const token = (await s.get('wawp_access_token')) || ctx.config.wawp?.accessToken || null;
|
||||
const instanceId = (await s.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null;
|
||||
const whatsapp = token && instanceId ? { accessToken: sealLinkValue(secret, token), instanceId } : null;
|
||||
return { email, whatsapp, updatedAt: (await s.get('messaging_updated_at')) || null };
|
||||
}
|
||||
|
||||
/** Old remembered requests (the `cleanup` job). */
|
||||
export async function forgetOldRequests(ctx: Ctx) {
|
||||
return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } });
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 11): Accounts takes WAWP's webhook itself, for a church
|
||||
* without Cross Events (a WAWP number sends replies to one address; with Events, Events receives
|
||||
* them and passes a STOP on with `whatsapp.optout`).
|
||||
*
|
||||
* POST /api/v2/webhooks/whatsapp?secret=… (WAWP's `message` event)
|
||||
*
|
||||
* WAWP doesn't sign webhooks, so the address carries a secret only Accounts and WAWP know
|
||||
* (Admin → Email and WhatsApp shows it to paste into WAWP). Always answers 200 quickly, so WAWP
|
||||
* never retries; only a STOP from a phone number is acted on.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { isStopKeyword, optOutNumber, phoneFromChatId } from '../accounts/whatsapp.js';
|
||||
|
||||
export const WHATSAPP_WEBHOOK_PATH = '/api/v2/webhooks/whatsapp';
|
||||
|
||||
/** The secret in the webhook's address, made on first use. */
|
||||
async function webhookSecret(ctx: Ctx): Promise<string> {
|
||||
const saved = await ctx.settings.get('wawp_webhook_secret');
|
||||
if (saved) return saved;
|
||||
const secret = crypto.randomBytes(24).toString('base64url');
|
||||
await ctx.settings.set('wawp_webhook_secret', secret);
|
||||
return secret;
|
||||
}
|
||||
|
||||
/** The address to paste into WAWP's webhook settings (event: message), and when it last called. */
|
||||
export async function whatsappWebhookUrl(ctx: Ctx) {
|
||||
return {
|
||||
url: `${ctx.config.publicUrl.replace(/\/$/, '')}${WHATSAPP_WEBHOOK_PATH}?secret=${encodeURIComponent(await webhookSecret(ctx))}`,
|
||||
lastSeenAt: await ctx.settings.get('wawp_webhook_last_seen'),
|
||||
};
|
||||
}
|
||||
|
||||
function secretMatches(given: string, secret: string) {
|
||||
return given.length === secret.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(secret));
|
||||
}
|
||||
|
||||
export async function handleWhatsappWebhook(ctx: Ctx, query: { secret?: unknown }, body: unknown): Promise<'ignored' | 'seen' | 'stopped'> {
|
||||
const secret = await ctx.settings.get('wawp_webhook_secret');
|
||||
if (!secret || !secretMatches(String(query.secret ?? ''), secret)) return 'ignored';
|
||||
await ctx.settings.set('wawp_webhook_last_seen', ctx.now().toISOString());
|
||||
const payload = ((body as { payload?: Record<string, unknown> })?.payload ?? {}) as { fromMe?: boolean; body?: unknown; from?: unknown };
|
||||
if (payload.fromMe || !isStopKeyword(payload.body)) return 'seen';
|
||||
const phone = phoneFromChatId(payload.from);
|
||||
// Groups, channels and senders WhatsApp only names by a "LID" have no number to opt out.
|
||||
if (!phone) return 'seen';
|
||||
await optOutNumber(ctx, phone, { keyword: String(payload.body).trim().toUpperCase().slice(0, 40), source: 'accounts', receivedAt: ctx.now() });
|
||||
// The one message after a STOP: what it did and how to undo it.
|
||||
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'the church';
|
||||
await ctx.messenger.whatsapp({ to: phone, text: `You won't get WhatsApp messages from ${church} any more. To turn them back on, go to ${ctx.config.publicUrl.replace(/\/$/, '')}/account.` })
|
||||
.catch((e: Error) => console.warn('[whatsapp webhook] confirmation not sent:', e.message));
|
||||
return 'stopped';
|
||||
}
|
||||
|
||||
export function whatsappWebhookRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
r.post(WHATSAPP_WEBHOOK_PATH, express.json({ limit: '256kb' }), async (req: Request, res: Response) => {
|
||||
try {
|
||||
await handleWhatsappWebhook(ctx, req.query as { secret?: unknown }, req.body);
|
||||
} catch (e) {
|
||||
console.error('[whatsapp webhook]', (e as Error).message);
|
||||
}
|
||||
res.json({ ok: true });
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -27,7 +27,7 @@ async function ownPart(ctx: Ctx, accountId: string) {
|
||||
return {
|
||||
product: 'accounts',
|
||||
sections: [
|
||||
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, whatsappOptedOut: a.whatsappOptedOut, whatsappOptedOutAt: a.whatsappOptedOutAt, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
|
||||
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
|
||||
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
|
||||
|
||||
@@ -10,6 +10,7 @@ import { branding, church } from '../church/profile.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
|
||||
import { setupNeeded } from '../setup/routes.js';
|
||||
import { currentNotice } from '../privacy/notice.js';
|
||||
import { DEMO_ASSETS_PATH, demoAsset } from '../demo/scenario.js';
|
||||
|
||||
const strip = (p: string) => p.replace(/^\/api/, '');
|
||||
|
||||
@@ -31,6 +32,14 @@ export function publicRouter(ctx: Ctx) {
|
||||
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
|
||||
}));
|
||||
|
||||
// 1.9.0: a demo scenario's logo and icon (drawn for the demo), which its church profile points at.
|
||||
r.get(`${strip(DEMO_ASSETS_PATH)}/:scenario/:file`, limit(600), (req, res) => {
|
||||
const svg = demoAsset(String(req.params.scenario), String(req.params.file));
|
||||
if (!svg) return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such demo image.' } });
|
||||
res.set({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'" });
|
||||
return res.send(svg);
|
||||
});
|
||||
|
||||
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
|
||||
res.set('Cache-Control', 'public, max-age=60');
|
||||
return church(ctx);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Accounts 1.9.0: a demo scenario's church and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { CHURCH_PATHS, churchSchema } from '@crosscode/contracts';
|
||||
import { demoPeople } from '@crosscode/demo';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { loadScenario } from '../src/demo/scenario.js';
|
||||
import { church } from '../src/church/profile.js';
|
||||
import { verifyPassword } from '../src/lib/passwords.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
const live = async () => h.db.account.findMany({ where: { status: { not: 'deleted' } } });
|
||||
|
||||
describe('loading a demo scenario', () => {
|
||||
test('the church becomes the scenario\'s, with its own logo and icon, and the products are told', async () => {
|
||||
const real = await h.makeAccount({ email: 'office@hope.test' });
|
||||
const admin = await h.makeAccount({ email: 'admin.demo@example.com', role: 'admin' });
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.church, 'Acacia Hill Church');
|
||||
const c = await church(h.ctx);
|
||||
assert.ok(churchSchema.safeParse(c).success);
|
||||
assert.equal(c.name, 'Acacia Hill Church');
|
||||
assert.equal(c.shortName, 'Acacia Hill');
|
||||
assert.equal(c.branding.colours.primary, '#2f6f4f');
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'soft' });
|
||||
assert.equal(c.branding.logoUrl, `${h.publicUrl}/api/demo-assets/community-family/logo.svg`);
|
||||
assert.equal(c.contact.email, 'office.acaciahill@example.com');
|
||||
assert.ok((await h.db.delivery.findMany({ where: { type: 'church.changed' } })).length >= 1);
|
||||
// Real people and admins are never touched.
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: real.id } }))!.status, 'active');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: admin.id } }))!.status, 'active');
|
||||
});
|
||||
|
||||
test('every person has an account with the id the other products work out, and the demo password', async () => {
|
||||
const people = demoPeople('community-family');
|
||||
const ids = new Set((await live()).map((a) => a.id));
|
||||
for (const p of people) assert.ok(ids.has(p.id), p.email);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: people[0]!.id } }))!;
|
||||
assert.equal(pastor.name, 'Thabo Nkosi');
|
||||
assert.equal(pastor.emailVerified, true);
|
||||
assert.ok(await verifyPassword('Demo@1234', pastor.passwordHash as string));
|
||||
});
|
||||
|
||||
test('loading it again changes nobody\'s id', async () => {
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.created, 0);
|
||||
assert.equal(r.removed, 0);
|
||||
assert.equal(r.updated, demoPeople('community-family').length);
|
||||
});
|
||||
|
||||
test('another scenario replaces the demo people; switching back brings them back with the same ids', async () => {
|
||||
const before = demoPeople('community-family');
|
||||
const r = await loadScenario(h.ctx, 'bold-plant');
|
||||
assert.equal(r.church, 'Harbour City Church');
|
||||
assert.equal(r.removed, before.length);
|
||||
assert.equal(r.created, demoPeople('bold-plant').length);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: before[0]!.id } }))!.status, 'deleted');
|
||||
assert.ok(await h.db.account.findUnique({ where: { email: 'office@hope.test' } }), 'a real person stays');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'admin.demo@example.com' } }))!.status, 'active', 'an admin stays');
|
||||
|
||||
const back = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(back.updated, before.length);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: before[0]!.id } }))!;
|
||||
assert.equal(pastor.status, 'active');
|
||||
assert.equal(pastor.email, before[0]!.email);
|
||||
});
|
||||
|
||||
test('a scenario with campuses has them in the profile', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church' }));
|
||||
// Riverside has about 2 450 people; only its profile is checked here.
|
||||
const c = await (async () => { await loadScenario(h.ctx, 'clean-campus'); return church(h.ctx); })();
|
||||
assert.deepEqual(c.campuses.map((x) => x.slug), ['stellenbosch', 'paarl', 'somerset-west']);
|
||||
assert.equal(c.serviceTimes.filter((s) => s.campus === 'stellenbosch').length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('demo logos', () => {
|
||||
test('served as SVG for a scenario, 404 for anything else', async () => {
|
||||
const res = await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/icon.svg`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get('content-type'), 'image/svg+xml; charset=utf-8');
|
||||
assert.match(await res.text(), /^<svg[^>]*>.*#e4572e/);
|
||||
const logo = await (await fetch(`${h.publicUrl}/api/demo-assets/heritage-parish/logo.svg`)).text();
|
||||
assert.match(logo, /St Columba's Church/);
|
||||
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/nowhere/icon.svg`)).status, 404);
|
||||
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/secrets.txt`)).status, 404);
|
||||
assert.equal((await fetch(`${h.publicUrl}${CHURCH_PATHS.profile}`)).status, 200);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
account: () => ({
|
||||
givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active',
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0,
|
||||
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false,
|
||||
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
}),
|
||||
recoveryCode: () => ({ usedAt: null }),
|
||||
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
|
||||
@@ -20,13 +20,13 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }),
|
||||
privacyNotice: () => ({ publishedById: null }),
|
||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||
productLink: () => ({ connectedById: null, importStartedAt: null }),
|
||||
productLink: () => ({ connectedById: null, importStartedAt: null, messagingWantedAt: null }),
|
||||
oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }),
|
||||
delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }),
|
||||
dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }),
|
||||
deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }),
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' };
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId', whatsAppOptOut: 'phone' };
|
||||
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
|
||||
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
|
||||
|
||||
@@ -117,6 +117,10 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
table().set(row[key], row);
|
||||
return clone(row);
|
||||
},
|
||||
createMany: async ({ data }: { data: Row[] }) => {
|
||||
for (const d of data) await api.create({ data: d });
|
||||
return { count: data.length };
|
||||
},
|
||||
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
// Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the church's email and WhatsApp settings for a product
|
||||
// that sends with them (messaging.get, messaging.changed), and the WhatsApp opt-out for every
|
||||
// product (whatsapp.optout, Accounts' own WAWP webhook, turning WhatsApp back on).
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH, messagingChangedSchema, messagingGetReplySchema, userUpdatedSchema } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
import { runDue } from '../src/links/deliveries.js';
|
||||
import { messagingChanged } from '../src/links/messaging.js';
|
||||
import { handleWhatsappWebhook, whatsappWebhookUrl } from '../src/links/whatsappWebhook.js';
|
||||
import { isStopKeyword, phoneFromChatId } from '../src/accounts/whatsapp.js';
|
||||
|
||||
let h: Harness;
|
||||
let messenger: MemoryMessenger;
|
||||
|
||||
before(async () => { h = await startHarness(); messenger = h.messenger as MemoryMessenger; });
|
||||
after(async () => { await h.close(); });
|
||||
beforeEach(async () => {
|
||||
h.received.length = 0;
|
||||
messenger.whatsappOn = true;
|
||||
messenger.whatsapps.length = 0;
|
||||
await h.db.delivery.deleteMany({});
|
||||
});
|
||||
|
||||
/** A request from the harness's linked product (signed with its link's secret). */
|
||||
async function ask(body: Record<string, unknown>) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: PRODUCT_ID, secret: h.linkSecret, rawBody: raw }) } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const sent = (path: string) => h.received.filter((r) => r.path === path).map((r) => JSON.parse(r.body) as Record<string, unknown>);
|
||||
|
||||
describe('messaging.get', () => {
|
||||
test('nothing set up: both parts null', async () => {
|
||||
const r = await ask({ type: 'messaging.get' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.ok(messagingGetReplySchema.safeParse(r.body).success);
|
||||
assert.equal(r.body.email, null);
|
||||
assert.equal(r.body.whatsapp, null);
|
||||
});
|
||||
|
||||
test('gives the settings with the password and token sealed for this link only, and never keeps the reply', async () => {
|
||||
await h.ctx.settings.setMany({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_user: 'hello@hope.test', smtp_pass: 'mail-pass', smtp_from: 'hello@hope.test', wawp_access_token: 'wa-token', wawp_instance_id: 'HOPE01' });
|
||||
const r = await ask({ type: 'messaging.get' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
const reply = messagingGetReplySchema.parse(r.body);
|
||||
assert.equal(reply.email?.host, 'smtp.hope.test');
|
||||
assert.equal(reply.email?.user, 'hello@hope.test');
|
||||
assert.notEqual(reply.email?.pass, 'mail-pass');
|
||||
assert.equal(openLinkValue(h.linkSecret, reply.email!.pass!), 'mail-pass');
|
||||
assert.equal(openLinkValue(h.linkSecret, reply.whatsapp!.accessToken), 'wa-token');
|
||||
assert.equal(reply.whatsapp?.instanceId, 'HOPE01');
|
||||
assert.doesNotMatch(JSON.stringify(r.body), /mail-pass|wa-token/);
|
||||
const link = await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } });
|
||||
assert.ok(link?.messagingWantedAt, 'remembered as wanting messaging.changed');
|
||||
assert.equal((await h.db.productRequest.findMany({ where: { type: 'messaging.get' } })).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('messaging.changed', () => {
|
||||
test('an admin changing WhatsApp tells the products that asked', async () => {
|
||||
await ask({ type: 'messaging.get' });
|
||||
await messagingChanged(h.ctx, { email: false, whatsapp: true });
|
||||
await runDue(h.ctx);
|
||||
const calls = sent(MESSAGING_CHANGED_PATH);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.ok(messagingChangedSchema.safeParse(calls[0]).success);
|
||||
assert.equal(calls[0]!.whatsapp, true);
|
||||
assert.equal(calls[0]!.email, false);
|
||||
assert.ok(h.received.find((x) => x.path === MESSAGING_CHANGED_PATH && h.signedByLink(x)), 'signed with the link');
|
||||
assert.ok(await h.ctx.settings.get('messaging_updated_at'));
|
||||
});
|
||||
|
||||
test('not to the product that made the change, nor for unrelated settings', async () => {
|
||||
await ask({ type: 'messaging.get' });
|
||||
await messagingChanged(h.ctx, { email: true, whatsapp: false }, PRODUCT_ID);
|
||||
await messagingChanged(h.ctx, { email: false, whatsapp: false });
|
||||
await runDue(h.ctx);
|
||||
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
|
||||
});
|
||||
|
||||
test('a product that never asked isn\'t told', async () => {
|
||||
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { messagingWantedAt: null } });
|
||||
await messagingChanged(h.ctx, { email: true, whatsapp: true });
|
||||
await runDue(h.ctx);
|
||||
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('whatsapp.optout', () => {
|
||||
test('opts out every account with the number, turns WhatsApp news off and tells the products', async () => {
|
||||
const a = await h.makeAccount({ email: 'stop1@hope.test', phone: '+27825550001', phoneVerified: true, newsWhatsApp: true });
|
||||
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550001', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.accounts, 1);
|
||||
const after = (await h.db.account.findUnique({ where: { id: a.id } }))!;
|
||||
assert.equal(after.whatsappOptedOut, true);
|
||||
assert.equal(after.newsWhatsApp, false);
|
||||
await runDue(h.ctx);
|
||||
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).find((b) => b.type === 'user.updated' && b.sub === a.id);
|
||||
assert.ok(updated, 'user.updated sent');
|
||||
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, true);
|
||||
});
|
||||
|
||||
test('keeps a number without an account: an account made with it later starts opted out', async () => {
|
||||
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550002', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
assert.equal(r.body.accounts, 0);
|
||||
const ensured = await ask({ type: 'people.ensure', name: 'Later Person', email: 'later@hope.test', phone: '+27825550002', returnUrl: `${h.productUrl}/` });
|
||||
assert.equal(ensured.status, 200, JSON.stringify(ensured.body));
|
||||
const a = (await h.db.account.findUnique({ where: { id: ensured.body.sub as string } }))!;
|
||||
assert.equal(a.whatsappOptedOut, true);
|
||||
});
|
||||
|
||||
test('a code for someone who replied STOP goes by email, never WhatsApp', async () => {
|
||||
await h.makeAccount({ email: 'stop3@hope.test', password: 'Correct-horse-1', phone: '+27825550003', twoFactorMethod: 'whatsapp', whatsappOptedOut: true });
|
||||
const r = await h.signIn(new Browser(), 'stop3@hope.test', 'Correct-horse-1');
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.stage, 'two_factor');
|
||||
assert.match(String(r.pending.sentTo), /@hope\.test$/);
|
||||
assert.equal(messenger.whatsapps.filter((w) => w.to === '+27825550003').length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accounts\' own WAWP webhook', () => {
|
||||
const message = (from: string, body: string, fromMe = false) => ({ event: 'message', payload: { from, body, fromMe } });
|
||||
|
||||
test('reads STOP and phone numbers as Cross Events does', () => {
|
||||
for (const s of ['STOP', ' stop ', 'Stop!', 'unsubscribe', 'STOPP', 'opt out']) assert.ok(isStopKeyword(s), s);
|
||||
for (const s of ['stop the music', 'please stop', '', 'STOPPED']) assert.ok(!isStopKeyword(s), s);
|
||||
assert.equal(phoneFromChatId('27825550004@c.us'), '+27825550004');
|
||||
assert.equal(phoneFromChatId('1234567890-123@g.us'), null);
|
||||
assert.equal(phoneFromChatId('12345@lid'), null);
|
||||
});
|
||||
|
||||
test('ignores a call without the secret', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
assert.match(url, /\/api\/v2\/webhooks\/whatsapp\?secret=/);
|
||||
await h.makeAccount({ email: 'stop4@hope.test', phone: '+27825550004' });
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret: 'wrong' }, message('27825550004@c.us', 'STOP')), 'ignored');
|
||||
const res = await fetch(`${h.publicUrl}/api/v2/webhooks/whatsapp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550004@c.us', 'STOP')) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop4@hope.test' } }))!.whatsappOptedOut, false);
|
||||
});
|
||||
|
||||
test('a STOP through the real address opts the number out and answers once', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
await h.makeAccount({ email: 'stop5@hope.test', phone: '+27825550005' });
|
||||
const path = url.slice(url.indexOf('/api/'));
|
||||
const res = await fetch(`${h.publicUrl}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550005@c.us', 'Stop')) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop5@hope.test' } }))!.whatsappOptedOut, true);
|
||||
assert.ok(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550005' } }));
|
||||
const replies = messenger.whatsapps.filter((w) => w.to === '+27825550005');
|
||||
assert.equal(replies.length, 1);
|
||||
assert.match(replies[0]!.text, /won't get WhatsApp messages from Hope Family Church/);
|
||||
assert.ok((await whatsappWebhookUrl(h.ctx)).lastSeenAt);
|
||||
});
|
||||
|
||||
test('other messages, and the church\'s own, change nothing', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
const secret = new URL(url).searchParams.get('secret');
|
||||
await h.makeAccount({ email: 'stop6@hope.test', phone: '+27825550006' });
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'Thanks!')), 'seen');
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'STOP', true)), 'seen');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop6@hope.test' } }))!.whatsappOptedOut, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('turning WhatsApp back on', () => {
|
||||
test('on the account page: every product may send it again, and the number\'s STOP is forgotten', async () => {
|
||||
await ask({ type: 'whatsapp.optout', phone: '+27825550007', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
const a = await h.makeAccount({ email: 'stop7@hope.test', password: 'Correct-horse-1', phone: '+27825550007', whatsappOptedOut: true, whatsappOptedOutAt: new Date() });
|
||||
const browser = new Browser();
|
||||
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
|
||||
const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'stop7@hope.test', password: 'Correct-horse-1' });
|
||||
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
|
||||
await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||
const me = await h.api(browser, 'GET', '/api/v2/me');
|
||||
assert.equal(me.body.whatsappOptedOut, true);
|
||||
// News on WhatsApp can't be ticked while it's off.
|
||||
await h.api(browser, 'PUT', '/api/v2/me/news', { email: false, whatsapp: true });
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.newsWhatsApp, false);
|
||||
const on = await h.api(browser, 'POST', '/api/v2/me/whatsapp-on');
|
||||
assert.equal(on.status, 200, JSON.stringify(on.body));
|
||||
assert.equal(on.body.whatsappOptedOut, false);
|
||||
assert.equal(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550007' } }), null);
|
||||
await runDue(h.ctx);
|
||||
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).filter((b) => b.type === 'user.updated' && b.sub === a.id).at(-1);
|
||||
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useExternalEffect } from "@/lib/hooks";
|
||||
type Me = {
|
||||
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
|
||||
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
|
||||
whatsappOptedOut?: boolean;
|
||||
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
|
||||
};
|
||||
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
|
||||
@@ -24,6 +25,7 @@ const EVENT: Record<string, string> = {
|
||||
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
|
||||
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
|
||||
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
|
||||
whatsapp_opted_out: "WhatsApp turned off (replied STOP)", whatsapp_opted_in: "WhatsApp turned back on",
|
||||
};
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
|
||||
@@ -291,8 +293,17 @@ function Privacy({ me, onDone, onFail }: Props) {
|
||||
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
|
||||
}}>
|
||||
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone || me.whatsappOptedOut} hint={!me.phone ? "Add your mobile number first." : me.whatsappOptedOut ? "WhatsApp is off: see below." : undefined} />
|
||||
</form>
|
||||
{me.whatsappOptedOut && (
|
||||
<div className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm">
|
||||
<p className="mb-2">You replied STOP to the church's WhatsApp number, so none of the church'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">
|
||||
|
||||
@@ -71,6 +71,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
{section === "messages" && <>
|
||||
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
|
||||
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
|
||||
<WhatsAppReplies />
|
||||
</>}
|
||||
{section === "notice" && <NoticeTab flash={flash} />}
|
||||
{section === "backups" && <Backups flash={flash} />}
|
||||
@@ -446,6 +447,29 @@ function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: strin
|
||||
);
|
||||
}
|
||||
|
||||
/** 1.9.0: where WAWP sends replies, so a STOP reaches Accounts (only needed without Cross Events). */
|
||||
function WhatsAppReplies() {
|
||||
const [data, setData] = useState<{ url: string; lastSeenAt: string | null; eventsLinked: boolean } | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<{ url: string; lastSeenAt: string | null; eventsLinked: boolean }>("GET", "/admin/settings/whatsapp-webhook").then((r) => { if (alive && r.ok) setData(r.data); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!data) return null;
|
||||
return (
|
||||
<Card>
|
||||
<Heading icon={<MessageCircle className="h-4 w-4" />} sub="Someone who replies STOP to the church's WhatsApp number gets no WhatsApp from any of the church's sites until they turn it back on on their account page.">WhatsApp replies (STOP)</Heading>
|
||||
{data.eventsLinked
|
||||
? <p className="text-sm text-gray-600">Cross Events receives the replies and passes a STOP on to Accounts. Keep WAWP'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 };
|
||||
|
||||
@@ -13,6 +13,16 @@ Write for the person updating servers: what the agent can now do from the Hub, a
|
||||
contracts version needs it. The developer log is the commit history of apps/agent.
|
||||
-->
|
||||
|
||||
## 1.7.0
|
||||
|
||||
- **Demo scenarios.** The Hub (2.26.0 and later) can load a whole demo church on a demo client:
|
||||
Accounts first, then Cross Events, the Website and the App, the same church and people in each.
|
||||
It's one job: the server loads **whatever the client has installed** and skips the rest, so a
|
||||
client with only Accounts and the Website gets both. Every product's release is checked first
|
||||
(Accounts 1.9.0, Events 3.8.0, Website 1.8.0); if one fails part-way, the report says which
|
||||
products are out of step. The agent also runs single demo jobs for Accounts and (from App
|
||||
1.0.0) the Church App. Single-product demo data works as before.
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
||||
"license": "UNLICENSED",
|
||||
|
||||
@@ -58,10 +58,20 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
|
||||
if (job.args.restart) out.push("--restart");
|
||||
return out;
|
||||
}
|
||||
case "seed-demo":
|
||||
case "seed-demo": {
|
||||
// 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] : [])];
|
||||
// 1.7.0: the App's and Accounts' too, and a demo scenario passed on (`--scenario`), so each
|
||||
// product can tell a scenario load from a single one.
|
||||
const a = job.args;
|
||||
const product = a.product && a.product !== "events" ? [a.product] : [];
|
||||
return ["demo", a.church, ...product, "--profile", a.profile,
|
||||
...(a.scenario ? ["--scenario", a.scenario] : []),
|
||||
...(a.adminEmail ? ["--admin-email", a.adminEmail] : [])];
|
||||
}
|
||||
case "seed-scenario":
|
||||
// 1.7.0: a whole demo scenario. No product named: the script loads every product the church
|
||||
// has on this server, Accounts first, and skips the others.
|
||||
return ["demo", job.args.church, "--scenario", job.args.scenario, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
|
||||
case "export":
|
||||
if (!opts.exportFile) throw new Error("export needs a file to write");
|
||||
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
|
||||
|
||||
@@ -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.6.0";
|
||||
export const AGENT_VERSION = "1.7.0";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
|
||||
@@ -52,6 +52,26 @@ describe("crosscode arguments for each job", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
|
||||
});
|
||||
|
||||
it("seed-scenario 1.7.0: one job, no product named, so the server seeds whatever the church has", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "community-family" } }))).toEqual(["demo", "demo2", "--scenario", "community-family"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "demo2", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
|
||||
expect(() => parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", products: ["website"] } })).toThrow();
|
||||
});
|
||||
|
||||
it("seed-demo 1.7.0: the App's and Accounts' demos, and a scenario passed on to every product", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "app", profile: "community-family" } }))).toEqual(["demo", "hope", "app", "--profile", "community-family"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "accounts", profile: "bold-youth", scenario: "bold-youth" } })))
|
||||
.toEqual(["demo", "hope", "accounts", "--profile", "bold-youth", "--scenario", "bold-youth"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "clean-campus", scenario: "clean-campus" } })))
|
||||
.toEqual(["demo", "hope", "website", "--profile", "clean-campus", "--scenario", "clean-campus"]);
|
||||
// Events keeps its old form (no product), with the scenario and the admin kept.
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "bold-youth", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "hope", "--profile", "bold-youth", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
|
||||
// A scenario's profile must be the scenario's for that product (the contracts refuse the job).
|
||||
expect(() => parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant", scenario: "bold-youth" } })).toThrow();
|
||||
});
|
||||
|
||||
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "env-read", args: { church: "hope", product: "accounts" } }))).toEqual(["env", "hope", "accounts"]);
|
||||
expect(crosscodeArgs(parsed({
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -0,0 +1,33 @@
|
||||
# Changelog — Church App
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
Being built for `app@1.0.0` (docs/APP-1.0-PLAN.md). One migration so far (`20261201000000_init`).
|
||||
|
||||
### Added
|
||||
|
||||
- **The foundation** (plan §1, §2, §10, §12): `backend/` (Express, Prisma, pg-boss) and
|
||||
`frontend/` (Next.js 16), as the Website.
|
||||
- The Hub: registers with a `CCP-` key from `HUB_LICENCE_KEY`, a heartbeat every 15 minutes with
|
||||
`hub.appStatsSchema` (the active-member band, the modules on; prayer, announcement and message
|
||||
counts 0 until their modules arrive), the licence checked offline.
|
||||
- Links: Connect and Disconnect (`crosscode.link/1`) with Accounts, Events and the Website; links
|
||||
itself to Accounts once the Hub lists it; `church.changed` from Accounts.
|
||||
- Signing in through Accounts (`@crosscode/auth-client`), back to the exact page. Everyone signed
|
||||
in is a Member (`Member`, keyed by the account's `sub`, a copy of the profile with the verified
|
||||
phone number and the WhatsApp opt-out). A sign-in lasts 8 days, renewed by each visit, never
|
||||
past 90 days from the sign-in (`SESSION_DAYS`, `SESSION_MAX_DAYS`). Back-channel logout.
|
||||
- Roles (Owner, Church admin, Content admin, Devotional writer, Prayer coordinator, Pastoral
|
||||
care): only with a 2FA sign-in (`TWO_FACTOR_NEEDED` otherwise; the admin's sign-in asks Accounts
|
||||
for a second step). The first Owner from `HUB_ADMIN_EMAIL`, verified.
|
||||
- Active members: `lastActiveAt`, at most one write a day in the church's timezone; the band in
|
||||
the heartbeat and on the dashboard.
|
||||
- Modules switched on and off (`modules` setting, `PUT /api/v1/admin/modules`, Owner and Church
|
||||
admin, audited).
|
||||
- `GET /api/v1/app`: the church profile, its colours made safe, font pairing and corners, the
|
||||
modules on, the timezone.
|
||||
- The frontend's shell: header, bottom tab bar, the church's footer, the manifest and icons
|
||||
(`/app-icon/192|512|maskable|apple|favicon`), the service worker (`public/sw.js`), "Add to home
|
||||
screen", the offline notice and page, Me, the admin's first dashboard, the sign-in problem page.
|
||||
- `env.template.json` (read by the Hub at the tag), `ecosystem.config.example.cjs` (ports 5400 / 3400
|
||||
in development).
|
||||
+44
-1
@@ -1,3 +1,46 @@
|
||||
# Church App
|
||||
|
||||
Placeholder: the church-branded web app (PWA) with House of Prayer. Built in phase 6 of ROADMAP-v3 (see §7 there).
|
||||
The church-branded web app (PWA) for its members, with the **House of Prayer** as its headline
|
||||
(ROADMAP-v3 §7, phase 6; plan and decisions in [docs/APP-1.0-PLAN.md](../../docs/APP-1.0-PLAN.md)).
|
||||
Served at `app.<church's address>` (or `<church>.crosscode.co.za`), added to the home screen, with no
|
||||
app-store release. Anyone can browse its public content; booking a prayer slot, a prayer request
|
||||
and notification settings need a sign-in through the church's Accounts. The admin is at `/admin`.
|
||||
|
||||
**State:** being built (from 2026-12-01) on the branch `feat/app-scaffold`, which is merged into
|
||||
main only when `app@1.0.0` is done (main keeps a placeholder until then). Not released;
|
||||
`app@1.0.0` is tagged when the plan is built. Done so far (the foundation, plan §1, §2, §10, §12):
|
||||
|
||||
- **Backend:** Express + Prisma + pg-boss (ES modules, as the Website). Registers with the Hub
|
||||
(`CCP-` licence key, product `app`) and sends the heartbeat with the active-member band the App
|
||||
tier is billed on; links itself to the church's Accounts once the Hub lists it; the church
|
||||
profile from Accounts (colours made safe, font pairing, corners).
|
||||
- **Signing in** (`backend/src/auth/`): anyone with an account at the church's Accounts becomes a
|
||||
Member. A sign-in lasts 8 days, renewed by each visit, up to 90 days (decision 7). Roles (Owner,
|
||||
Church admin, Content admin, Devotional writer, Prayer coordinator, Pastoral care) are the App's
|
||||
own; every one needs a sign-in with 2FA to use what it adds. The first Owner is whoever signs in
|
||||
with the Hub's admin email (`HUB_ADMIN_EMAIL`), verified in Accounts. Accounts' `user.updated`
|
||||
(WhatsApp STOP included), `user.export` and `user.deleted` are handled.
|
||||
- **Active members:** the last day a member used the App signed in, written at most once a day (in
|
||||
the church's timezone); the heartbeat reports only the band.
|
||||
- **Modules:** House of Prayer, Prayer requests, Announcements, Devotionals and Events can each be
|
||||
switched off (`PUT /api/v1/admin/modules`); Home and the tab bar only show what's on.
|
||||
- **Frontend:** Next.js 16, mobile first: the header, the bottom tab bar (Home, Prayer, Events,
|
||||
Devotional, Me), the church's colours, fonts and footer; the manifest and icons from the profile
|
||||
(its icon, else its initials on its colour; a maskable one too); the service worker (offline
|
||||
shell, pages kept for offline, a signed-in member's pages forgotten once they're signed out, no
|
||||
push); "Add to home screen" (Android's prompt, the iPhone's steps); Me; the admin's first
|
||||
dashboard. The modules' screens say what's coming.
|
||||
|
||||
**Still to come** (plan §3–§15): the House of Prayer, prayer requests, announcements,
|
||||
devotionals (Cross Code's from the Hub: the next 2 weeks, today included, fetched each night; and
|
||||
the church's own), events and the feed, email and WhatsApp, the rest of the admin, the export,
|
||||
backups, the demo church and scenarios, `scripts/products/app.sh`, e2e and Lighthouse.
|
||||
|
||||
- `backend/`: `npm run dev`, `npm test` (Node's test runner through tsx), `npm run build`. The
|
||||
schema is in `prisma/schema.prisma`.
|
||||
- `frontend/`: `npm run dev` (port 3400, sends /api to the backend on 5400).
|
||||
|
||||
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `APP_URL=http://localhost:3400`),
|
||||
`npx prisma migrate deploy`, then `npm run dev` in both folders. Set `LINKS_ALLOW_PRIVATE=true` to
|
||||
link to an Accounts on http://localhost. The service worker only runs in a production build
|
||||
(`npm run build && npm start`).
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# What's new in the Church App
|
||||
|
||||
What each version changes for the church, in plain language (read by the Hub like the Website's
|
||||
and Cross Events' WHATS-NEW.md; a section shows once its version is tagged).
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
dist/
|
||||
src/generated/
|
||||
.env
|
||||
/backups/
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@crosscode/app-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "Church App: the member, admin and public API, sign-in through Accounts, the Hub client and background jobs",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"cron-parser": "^5.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"pg-boss": "^11.1.2",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"prisma": "^7.10.1",
|
||||
"supertest": "^7.3.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
|
||||
import 'dotenv/config';
|
||||
import { defineConfig } from 'prisma/config';
|
||||
|
||||
export default defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: { path: 'prisma/migrations' },
|
||||
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
|
||||
datasource: { url: process.env.DATABASE_URL ?? '' },
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
-- Church App 1.0.0: the foundation (docs/APP-1.0-PLAN.md §1, §2, §10, §12): members and roles,
|
||||
-- sessions, links to the church's other products, the audit log and settings.
|
||||
|
||||
-- CreateSchema
|
||||
CREATE SCHEMA IF NOT EXISTS "public";
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AppRole" AS ENUM ('owner', 'church_admin', 'content_admin', 'devotional_writer', 'prayer_coordinator', 'pastoral_care');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Member" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"phone" TEXT,
|
||||
"whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false,
|
||||
"roles" "AppRole"[] DEFAULT ARRAY[]::"AppRole"[],
|
||||
"lastActiveAt" TIMESTAMP(3),
|
||||
"lastSignInAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Member_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"memberId" TEXT NOT NULL,
|
||||
"sid" TEXT,
|
||||
"mfa" BOOLEAN NOT NULL DEFAULT false,
|
||||
"idToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"absoluteExpiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProductLink" (
|
||||
"installId" TEXT NOT NULL,
|
||||
"product" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"publicKey" TEXT NOT NULL,
|
||||
"secret" TEXT NOT NULL,
|
||||
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"connectedById" TEXT,
|
||||
"showEvents" BOOLEAN NOT NULL DEFAULT true,
|
||||
"lastSyncAt" TIMESTAMP(3),
|
||||
"lastGoodAt" TIMESTAMP(3),
|
||||
"lastSyncError" TEXT,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "LinkNonce" (
|
||||
"nonce" TEXT NOT NULL,
|
||||
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorRole" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"targetType" TEXT NOT NULL,
|
||||
"targetId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AppSetting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Member_lastActiveAt_idx" ON "Member"("lastActiveAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_tokenHash_key" ON "Session"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_memberId_idx" ON "Session"("memberId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_sid_idx" ON "Session"("sid");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Session" ADD CONSTRAINT "Session_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,119 @@
|
||||
// Church App 1.0.0 (docs/APP-1.0-PLAN.md). One database per church.
|
||||
//
|
||||
// The foundation (§1, §2, §10, §12): members and their roles, sessions, links to the church's other
|
||||
// products, the audit log and settings. The modules' tables (House of Prayer, prayer requests,
|
||||
// announcements, devotionals, events) come with each module. Shared facts (name, logo, colours,
|
||||
// timezone, contact) are the church profile's, in Accounts (§9), and are never stored here.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
|
||||
output = "../src/generated/prisma"
|
||||
moduleFormat = "esm"
|
||||
importFileExtension = "js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
/// The App's roles above Member (§10). Held here, per product: an Events or Website role gives
|
||||
/// nothing in the App. A person can have several; every one of them needs 2FA (§2, decision 7).
|
||||
enum AppRole {
|
||||
owner
|
||||
church_admin
|
||||
content_admin
|
||||
devotional_writer
|
||||
prayer_coordinator
|
||||
pastoral_care
|
||||
}
|
||||
|
||||
/// Someone who has signed in to the App: keyed by their account's `sub` from Accounts. Everyone
|
||||
/// signed in is a Member; `roles` adds what the admin can do. A copy of the Accounts profile, kept
|
||||
/// up to date by `user.updated`.
|
||||
model Member {
|
||||
id String @id
|
||||
name String
|
||||
email String
|
||||
/// The verified number from Accounts (reminders by WhatsApp), or null.
|
||||
phone String?
|
||||
/// The person replied STOP to the church's WhatsApp number (decision 11): no WhatsApp of any kind.
|
||||
whatsappOptedOut Boolean @default(false)
|
||||
roles AppRole[] @default([])
|
||||
/// The last day they used the App signed in (written at most once a day): active members (§10).
|
||||
lastActiveAt DateTime?
|
||||
lastSignInAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
sessions Session[]
|
||||
|
||||
@@index([lastActiveAt])
|
||||
}
|
||||
|
||||
/// A sign-in (the `cca_session` cookie holds the token; only its SHA-256 is kept). It lasts 8 days,
|
||||
/// renewed by each visit, and never past `absoluteExpiresAt`, 90 days from the sign-in (§2).
|
||||
/// `sid` is Accounts' session id, so a back-channel logout ends the matching sessions.
|
||||
model Session {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
memberId String
|
||||
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
|
||||
sid String?
|
||||
/// Whether Accounts did a second step for this sign-in (`amr` has `mfa`): needed for any role.
|
||||
mfa Boolean @default(false)
|
||||
/// The ID token (encrypted), for "Sign out" at Accounts (`id_token_hint`).
|
||||
idToken String?
|
||||
createdAt DateTime @default(now())
|
||||
lastSeenAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
absoluteExpiresAt DateTime
|
||||
|
||||
@@index([memberId])
|
||||
@@index([sid])
|
||||
}
|
||||
|
||||
/// A link to another of the church's products (`crosscode.link/1`): Accounts, for signing in and
|
||||
/// the shared email and WhatsApp settings, and Events / the Website for the event feed (§7, §8).
|
||||
/// The secret is encrypted.
|
||||
model ProductLink {
|
||||
installId String @id
|
||||
product String
|
||||
url String
|
||||
publicKey String
|
||||
secret String
|
||||
connectedAt DateTime @default(now())
|
||||
connectedById String?
|
||||
/// Show this sibling's events in the App (the event feed, §7). Accounts has none.
|
||||
showEvents Boolean @default(true)
|
||||
lastSyncAt DateTime?
|
||||
lastGoodAt DateTime?
|
||||
lastSyncError String?
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
/// Nonces of link messages seen in the last hour (replays are refused).
|
||||
model LinkNonce {
|
||||
nonce String @id
|
||||
seenAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// Who changed what in the admin (§10, Audit log).
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
actorId String?
|
||||
actorRole String
|
||||
action String
|
||||
targetType String
|
||||
targetId String?
|
||||
metadata Json?
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model AppSetting {
|
||||
key String @id
|
||||
value String
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* The admin API (APP-1.0-PLAN §10), under /api/v1/admin. Every route needs a role above Member and
|
||||
* a sign-in with 2FA (auth/sessions.ts `requireRole`).
|
||||
*
|
||||
* GET /overview the dashboard: active members and band, modules, the Hub and Accounts links
|
||||
* PUT /modules switch modules on or off (Owner, Church admin)
|
||||
*
|
||||
* The rest comes with each module (§10): House of Prayer, requests, announcements, devotionals,
|
||||
* events, members and roles, settings, audit and access logs.
|
||||
*/
|
||||
import express from 'express';
|
||||
import { z } from 'zod';
|
||||
import { APP_MODULES } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError, handle, sameOrigin } from '../http.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { requireRole } from '../auth/sessions.js';
|
||||
import { licenceStatus } from '../hub/licence.js';
|
||||
import { activeMembers } from '../members/activity.js';
|
||||
import { enabledModules, setModules } from '../modules.js';
|
||||
|
||||
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
|
||||
|
||||
export function adminRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
|
||||
r.use(express.json({ limit: '64kb' }));
|
||||
r.use((_req, res, next) => {
|
||||
res.set('Cache-Control', 'no-store');
|
||||
next();
|
||||
});
|
||||
|
||||
r.get('/overview', requireRole(ctx), handle(async () => {
|
||||
const [members, modules, licence, accounts, lastHeartbeatAt] = await Promise.all([
|
||||
activeMembers(ctx),
|
||||
enabledModules(ctx),
|
||||
licenceStatus(ctx),
|
||||
ctx.db.productLink.findFirst({ where: { product: 'accounts' } }),
|
||||
ctx.settings.get('hub_last_heartbeat_at'),
|
||||
]);
|
||||
return {
|
||||
activeMembers90d: members,
|
||||
modules,
|
||||
hub: { connected: licence.connected, state: licence.state, endsAt: licence.endsAt, daysLeft: licence.daysLeft, lastHeartbeatAt },
|
||||
accounts: accounts ? { url: accounts.url, connectedAt: accounts.connectedAt } : null,
|
||||
};
|
||||
}));
|
||||
|
||||
r.put('/modules', requireRole(ctx, ['owner', 'church_admin']), handle(async (req) => {
|
||||
const parsed = modulesBody.safeParse(req.body);
|
||||
if (!parsed.success) throw new ApiError(400, 'VALIDATION', `Send the modules to switch as { "<module>": true | false }: ${APP_MODULES.join(', ')}.`);
|
||||
const change = Object.fromEntries(Object.entries(parsed.data).filter(([, v]) => typeof v === 'boolean')) as Record<string, boolean>;
|
||||
const modules = await setModules(ctx, change);
|
||||
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'modules_changed', targetType: 'settings', targetId: 'modules', metadata: change, ip: clientIp(req) });
|
||||
return { modules };
|
||||
}));
|
||||
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* The Express app (docs/APP-1.0-PLAN.md §1). Everything is under /api, so the App and its API
|
||||
* share one address (as the Website, Events and Accounts): nginx sends /api to this backend and the
|
||||
* rest to Next.js.
|
||||
*
|
||||
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
|
||||
* /api/v1/app the church, its colours and style, the modules on (public)
|
||||
* /api/auth/… signing in through the church's Accounts
|
||||
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
|
||||
* /api/links/v1/… Connect and Disconnect with the church's other products
|
||||
* /api/church/v1/changed Accounts: the church profile changed
|
||||
* /api/v1/admin/… the admin (a role above Member, with 2FA)
|
||||
*
|
||||
* To come with the modules (§1): the public content API, the member API (/api/v1/me/…), live
|
||||
* coverage (/api/v1/prayer/stream) and the event feed.
|
||||
*/
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { adminRouter } from './admin/routes.js';
|
||||
import { authRouter } from './auth/routes.js';
|
||||
import { dbUp } from './hub/client.js';
|
||||
import { ApiError, handle, sendError } from './http.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
import { linksRouter } from './links/routes.js';
|
||||
import { appInfo } from './public/app.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
|
||||
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
// The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11).
|
||||
res.setHeader('X-Robots-Tag', 'noindex');
|
||||
next();
|
||||
});
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
const db = await dbUp(ctx);
|
||||
res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'app', version: appVersion(), db });
|
||||
});
|
||||
|
||||
app.get('/api/v1/app', handle(async (_req, res) => {
|
||||
// Short: a change to the church profile or the modules shows within a minute.
|
||||
res.set('Cache-Control', 'public, max-age=30');
|
||||
return appInfo(ctx);
|
||||
}));
|
||||
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
app.use('/api/v1/admin', adminRouter(ctx));
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
|
||||
});
|
||||
|
||||
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
if (res.headersSent) return next(err);
|
||||
if (err instanceof ApiError) return sendError(res, err);
|
||||
const e = err as { type?: string; status?: number };
|
||||
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
|
||||
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, 'BAD_REQUEST', "That request isn't valid."));
|
||||
return sendError(res, err);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* The church's Accounts, as the App's OIDC client (APP-1.0-PLAN §2), built on
|
||||
* `@crosscode/auth-client` from the Accounts link (links/connect.ts). Its address is the one the
|
||||
* Hub listed; the client id is the App's Hub install id and the client secret comes from the
|
||||
* link's secret, so there's no `.env` setting for any of it (as Cross Events 3.x and the Website).
|
||||
*/
|
||||
import type * as AuthClient from '@crosscode/auth-client';
|
||||
import type { AccountsClient } from '@crosscode/auth-client';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { linkAccountsNow } from '../links/connect.js';
|
||||
|
||||
export type AuthClientModule = typeof AuthClient;
|
||||
|
||||
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
|
||||
|
||||
export class AccountsUnavailable extends ApiError {
|
||||
/** `not_linked` (no link to Accounts yet) or `unreachable` (linked, but it didn't answer). */
|
||||
constructor(message: string, public reason: 'not_linked' | 'unreachable' = 'unreachable') {
|
||||
super(503, 'ACCOUNTS_UNAVAILABLE', message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The Accounts link, or null while the App isn't linked to Accounts. */
|
||||
export async function accountsLink(ctx: Ctx) {
|
||||
return ctx.db.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
|
||||
}
|
||||
|
||||
const cache = new WeakMap<Ctx, { key: string; client: Promise<AccountsClient> }>();
|
||||
|
||||
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
|
||||
export async function accounts(ctx: Ctx): Promise<AccountsClient> {
|
||||
let link = await accountsLink(ctx);
|
||||
if (!link) {
|
||||
// Link now rather than wait for the next heartbeat.
|
||||
await linkAccountsNow(ctx);
|
||||
link = await accountsLink(ctx);
|
||||
}
|
||||
if (!link) throw new AccountsUnavailable('The App isn\'t linked to the church\'s Accounts yet.', 'not_linked');
|
||||
const clientId = await ctx.settings.get('hub_install_id');
|
||||
if (!clientId) throw new AccountsUnavailable('The App isn\'t connected to the Hub yet.', 'not_linked');
|
||||
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
|
||||
let hit = cache.get(ctx);
|
||||
if (!hit || hit.key !== key) {
|
||||
const client = ctx.authClient().then((m) => m.accountsClient({
|
||||
accountsUrl: link.url,
|
||||
productUrl: ctx.config.publicUrl,
|
||||
clientId,
|
||||
linkSecret: ctx.secrets.decrypt(link.secret),
|
||||
allowInsecure: !ctx.config.production && link.url.startsWith('http:'),
|
||||
}));
|
||||
// A failed discovery (Accounts down for a moment) is tried again next time.
|
||||
client.catch(() => { if (cache.get(ctx)?.key === key) cache.delete(ctx); });
|
||||
hit = { key, client };
|
||||
cache.set(ctx, hit);
|
||||
}
|
||||
try {
|
||||
return await hit.client;
|
||||
} catch (e) {
|
||||
throw new AccountsUnavailable(`The church's Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* Signing in to the App through the church's Accounts (APP-1.0-PLAN §2, as the Website and Cross
|
||||
* Events 3.x), under /api:
|
||||
*
|
||||
* GET /auth/signin?returnTo=…[&mfa=1] PKCE + state in a short-lived cookie, then off to Accounts
|
||||
* GET /auth/callback back from Accounts: the App's own session, then returnTo
|
||||
* GET /auth/me who's signed in, and the roles this sign-in may use
|
||||
* POST /auth/signout ends this session, then Accounts' sign-out (all the church's sites)
|
||||
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
|
||||
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
|
||||
*
|
||||
* Anyone with an account at the church's Accounts can sign in and becomes a Member. Roles are the
|
||||
* App's own (never in the claims). The first Owner is whoever signs in with the church's admin
|
||||
* email from the Hub (HUB_ADMIN_EMAIL), verified in Accounts, while the App has no Owner (§10).
|
||||
*
|
||||
* Members sign in without a second step; someone with a role who comes back from Accounts without
|
||||
* one while heading for the admin is sent once more with `mfa=1` (§2). Sign-in always returns to the
|
||||
* exact page it started from (ROADMAP-v3 §3).
|
||||
*/
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { AppRole } from '../generated/prisma/client.js';
|
||||
import { handle, sendError } from '../http.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { accounts, AccountsUnavailable } from './accounts.js';
|
||||
import { cookieOptions, currentSession, readCookies, SESSION_COOKIE, startSession } from './sessions.js';
|
||||
|
||||
const PENDING_COOKIE = 'cca_signin';
|
||||
const MFA_COOKIE = 'cca_signin_mfa';
|
||||
const COOKIE_PATH = '/api/auth';
|
||||
const PENDING_MINUTES = 10;
|
||||
|
||||
/** A page of the App, absolute (in development the API and the pages are on different ports). */
|
||||
const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${path}`;
|
||||
|
||||
/** The problem page: a short reason and "Try again" with the same return path. */
|
||||
const problem = (ctx: Ctx, res: Response, code: string, returnTo = '/') =>
|
||||
res.redirect(303, page(ctx, `/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
|
||||
|
||||
const unavailableCode = (e: AccountsUnavailable) => (e.reason === 'not_linked' ? 'ACCOUNTS_NOT_LINKED' : 'ACCOUNTS_UNAVAILABLE');
|
||||
|
||||
/** Whether a page is part of the admin (where a role needs its second step). */
|
||||
const isAdminPath = (path: string) => path === '/admin' || path.startsWith('/admin/') || path.startsWith('/admin?');
|
||||
|
||||
type MemberRow = { id: string; name: string; email: string; roles: AppRole[] };
|
||||
|
||||
/** The profile fields the App keeps a copy of. */
|
||||
const profileData = (p: { name: string; email: string; phone_number: string | null; phone_number_verified: boolean; whatsapp_opted_out?: boolean }) => ({
|
||||
name: p.name,
|
||||
email: p.email.toLowerCase(),
|
||||
phone: p.phone_number_verified ? p.phone_number : null,
|
||||
whatsappOptedOut: p.whatsapp_opted_out ?? false,
|
||||
});
|
||||
|
||||
/**
|
||||
* The member for a sign-in: found by `sub` (their copy brought up to date), else added. The first
|
||||
* one to sign in with the Hub's admin email (verified) while there's no Owner becomes the Owner.
|
||||
*/
|
||||
export async function memberForClaims(ctx: Ctx, claims: IdentityClaims): Promise<{ member: MemberRow; firstOwner: boolean }> {
|
||||
const data = { ...profileData(claims), lastSignInAt: ctx.now() };
|
||||
const known = await ctx.db.member.findUnique({ where: { id: claims.sub } });
|
||||
const adminEmail = ctx.config.hubAdminEmail;
|
||||
const mayBeFirstOwner = !!adminEmail && claims.email_verified && claims.email.toLowerCase() === adminEmail
|
||||
&& !(known?.roles.includes('owner')) && !(await ctx.db.member.findFirst({ where: { roles: { has: 'owner' } } }));
|
||||
if (known) {
|
||||
const roles = mayBeFirstOwner ? [...known.roles, 'owner' as const] : known.roles;
|
||||
const member = await ctx.db.member.update({ where: { id: known.id }, data: { ...data, roles } });
|
||||
return { member, firstOwner: mayBeFirstOwner };
|
||||
}
|
||||
const member = await ctx.db.member.create({ data: { id: claims.sub, ...data, roles: mayBeFirstOwner ? ['owner'] : [] } });
|
||||
return { member, firstOwner: mayBeFirstOwner };
|
||||
}
|
||||
|
||||
export function authRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
|
||||
r.get('/auth/signin', async (req, res) => {
|
||||
const returnTo = safeReturnPath(req.query.returnTo);
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const requireTwoFactor = req.query.mfa === '1';
|
||||
const { url, cookie } = await auth.startSignIn(returnTo, { requireTwoFactor });
|
||||
const opts = { ...cookieOptions(ctx, COOKIE_PATH), maxAge: PENDING_MINUTES * 60e3 };
|
||||
res.cookie(PENDING_COOKIE, cookie, opts);
|
||||
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', opts);
|
||||
else res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
return res.redirect(303, url);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e), returnTo);
|
||||
console.error('[auth] Starting a sign-in failed:', e);
|
||||
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
|
||||
}
|
||||
});
|
||||
|
||||
r.get(OIDC_CLIENT_PATHS.callback.replace(/^\/api/, ''), async (req, res) => {
|
||||
const cookies = readCookies(req);
|
||||
const askedForTwoFactor = cookies[MFA_COOKIE] === '1';
|
||||
res.clearCookie(PENDING_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
let result: Awaited<ReturnType<Awaited<ReturnType<typeof accounts>>['finishSignIn']>>;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
result = await auth.finishSignIn(new URL(req.originalUrl, ctx.config.publicUrl), cookies[PENDING_COOKIE]);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e));
|
||||
const code = (e as { code?: string }).code;
|
||||
// The person pressed Cancel at Accounts, or the pending cookie expired.
|
||||
if (req.query.error === 'access_denied') return res.redirect(303, page(ctx, '/'));
|
||||
return problem(ctx, res, code === 'NO_PENDING' ? 'EXPIRED' : 'SIGNIN_FAILED');
|
||||
}
|
||||
const { claims, returnTo, idToken } = result;
|
||||
const { member, firstOwner } = await memberForClaims(ctx, claims);
|
||||
const mfa = claims.amr.includes('mfa');
|
||||
if (!mfa && member.roles.length && isAdminPath(returnTo)) {
|
||||
// Once: ask Accounts again with a second step. If it still comes back without one, say why.
|
||||
if (askedForTwoFactor) return problem(ctx, res, 'TWO_FACTOR_NEEDED', returnTo);
|
||||
return res.redirect(303, page(ctx, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`));
|
||||
}
|
||||
// Accounts' session id, when its token carries one (not part of crosscode.identity/1's claims).
|
||||
const sid = (claims as unknown as { sid?: string }).sid ?? null;
|
||||
await startSession(ctx, res, { memberId: member.id, sid, mfa, idToken });
|
||||
await audit(ctx, { actorId: member.id, actorRole: member.roles.length ? member.roles.join(',') : 'member', action: firstOwner ? 'first_owner_signed_in' : 'member_signed_in', targetType: 'member', targetId: member.id, metadata: { mfa }, ip: clientIp(req) });
|
||||
return res.redirect(303, page(ctx, returnTo));
|
||||
});
|
||||
|
||||
r.get('/auth/me', handle(async (req, res) => {
|
||||
const s = await currentSession(ctx, req, res);
|
||||
res.set('Cache-Control', 'no-store');
|
||||
if (!s) {
|
||||
res.status(401).json({ error: { code: 'SIGNED_OUT', message: 'Please sign in.' } });
|
||||
return undefined;
|
||||
}
|
||||
return { member: s.member, mfa: s.mfa, activeRoles: s.activeRoles };
|
||||
}));
|
||||
|
||||
r.post('/auth/signout', async (req, res) => {
|
||||
const s = await currentSession(ctx, req).catch(() => null);
|
||||
res.clearCookie(SESSION_COOKIE, cookieOptions(ctx));
|
||||
if (s) {
|
||||
await ctx.db.session.delete({ where: { id: s.sessionId } }).catch(() => {});
|
||||
await audit(ctx, { actorId: s.member.id, actorRole: s.member.roles.join(',') || 'member', action: 'member_signed_out', targetType: 'member', targetId: s.member.id, ip: clientIp(req) });
|
||||
}
|
||||
// Then Accounts, so the person is signed out of all the church's sites and comes back here.
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
return res.redirect(303, auth.signOutUrl(s?.idToken ?? undefined));
|
||||
} catch {
|
||||
return res.redirect(303, page(ctx, '/'));
|
||||
}
|
||||
});
|
||||
|
||||
r.post(OIDC_CLIENT_PATHS.backchannelLogout.replace(/^\/api/, ''), express.urlencoded({ extended: false, limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const { sub, sid } = await auth.verifyLogoutToken(String(req.body?.logout_token ?? ''));
|
||||
// That Accounts session's sign-ins here, and any whose session id wasn't known.
|
||||
await ctx.db.session.deleteMany({ where: sid ? { memberId: sub, OR: [{ sid }, { sid: null }] } : { memberId: sub } });
|
||||
res.set('Cache-Control', 'no-store').status(200).end();
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code;
|
||||
res.status(code === 'BAD_TOKEN' ? 400 : 503).json({ error: 'invalid_request' });
|
||||
}
|
||||
});
|
||||
|
||||
r.post(ACCOUNTS_CALL_PATH.replace(/^\/api/, ''), express.raw({ type: '*/*', limit: '256kb' }), async (req, res) => {
|
||||
let call: AccountsCall;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
call = auth.verifyAccountsCall(req.body as Buffer, req.headers);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return sendError(res, e);
|
||||
return res.status(401).json({ error: { code: (e as { code?: string }).code ?? 'BAD_SIGNATURE', message: (e as Error).message } });
|
||||
}
|
||||
try {
|
||||
return res.json(await handleAccountsCall(ctx, call, req));
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accounts' signed calls (§11). So far the App keeps a member's profile copy, roles and sign-ins;
|
||||
* each module adds its own records to the export and the delete as it arrives (commitments, "I
|
||||
* prayed" marks, requests, testimonies, notification settings). Someone the App doesn't know is
|
||||
* answered as done.
|
||||
*/
|
||||
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
|
||||
const member = await ctx.db.member.findUnique({ where: { id: call.sub } });
|
||||
switch (call.type) {
|
||||
case 'user.updated': {
|
||||
if (member) await ctx.db.member.update({ where: { id: member.id }, data: profileData(call.profile) });
|
||||
return { schema: IDENTITY_SCHEMA, ok: true };
|
||||
}
|
||||
case 'user.export': {
|
||||
const reply: UserExportReply = {
|
||||
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'app', generatedAt: ctx.now().toISOString(),
|
||||
sections: member ? [{
|
||||
key: 'app_member',
|
||||
title: 'You in the church\'s App',
|
||||
records: [{ name: member.name, email: member.email, roles: member.roles, since: member.createdAt.toISOString(), lastSignIn: member.lastSignInAt?.toISOString() ?? null, lastUsed: member.lastActiveAt?.toISOString() ?? null }],
|
||||
}] : [],
|
||||
};
|
||||
return reply;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
if (member) {
|
||||
await ctx.db.session.deleteMany({ where: { memberId: member.id } });
|
||||
await ctx.db.member.delete({ where: { id: member.id } });
|
||||
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'member_deleted', targetType: 'member', targetId: member.id, metadata: { roles: member.roles }, ip: clientIp(req) });
|
||||
}
|
||||
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Sessions and roles (APP-1.0-PLAN §2, §10, decision 7). After a sign-in through Accounts the App
|
||||
* keeps its own session: an HttpOnly cookie with a random token, of which only the SHA-256 is
|
||||
* stored.
|
||||
*
|
||||
* **Staying signed in:** a sign-in lasts `sessionDays` (8). Using the App renews it for another 8,
|
||||
* but never past `sessionMaxDays` (90) from the sign-in; after that, or after 8 days away, the
|
||||
* member signs in again. Signing out anywhere (Accounts' back-channel logout) ends it.
|
||||
*
|
||||
* **Roles** are the App's own (keyed by the account's `sub`); Accounts never says them. Everyone
|
||||
* signed in is a Member. Every role above Member needs a sign-in with a second step (`mfa`) to use
|
||||
* what the role adds: without it the person is a Member until they sign in again with 2FA.
|
||||
*/
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { AppRole } from '../generated/prisma/client.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { recordActive } from '../members/activity.js';
|
||||
|
||||
export const SESSION_COOKIE = 'cca_session';
|
||||
|
||||
const DAY = 24 * 3600e3;
|
||||
/** A session's expiry is pushed forward at most this often (a visit doesn't write on every request). */
|
||||
const RENEW_EVERY_MS = 60_000;
|
||||
|
||||
/** Every role, as the admin lists them (§10). */
|
||||
export const ROLES: readonly AppRole[] = ['owner', 'church_admin', 'content_admin', 'devotional_writer', 'prayer_coordinator', 'pastoral_care'];
|
||||
|
||||
/** Owner and Church admin can do everything a narrower role can (§10). */
|
||||
export const FULL_ROLES: readonly AppRole[] = ['owner', 'church_admin'];
|
||||
|
||||
/** Whether someone with `roles` may do what `needed` allows (any of them, or a full role). */
|
||||
export function hasRole(roles: readonly AppRole[], needed: readonly AppRole[]): boolean {
|
||||
return roles.some((r) => FULL_ROLES.includes(r) || needed.includes(r));
|
||||
}
|
||||
|
||||
export function readCookies(req: Request): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of String(req.headers.cookie || '').split(';')) {
|
||||
const i = part.indexOf('=');
|
||||
if (i > 0) {
|
||||
try {
|
||||
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
||||
} catch {
|
||||
// A cookie this site didn't write: ignored.
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieOptions = (ctx: Ctx, path = '/') => ({ httpOnly: true, sameSite: 'lax' as const, secure: ctx.config.production, path });
|
||||
|
||||
/** The rolling expiry: `sessionDays` from now, never past the absolute limit. Pure. */
|
||||
export function rollingExpiry(now: Date, absoluteExpiresAt: Date, sessionDays: number): Date {
|
||||
return new Date(Math.min(now.getTime() + sessionDays * DAY, absoluteExpiresAt.getTime()));
|
||||
}
|
||||
|
||||
export async function startSession(ctx: Ctx, res: Response, s: { memberId: string; sid: string | null; mfa: boolean; idToken: string }) {
|
||||
const token = randomToken();
|
||||
const now = ctx.now();
|
||||
const absoluteExpiresAt = new Date(now.getTime() + ctx.config.sessionMaxDays * DAY);
|
||||
const expiresAt = rollingExpiry(now, absoluteExpiresAt, ctx.config.sessionDays);
|
||||
await ctx.db.session.create({
|
||||
data: { tokenHash: hashToken(token), memberId: s.memberId, sid: s.sid, mfa: s.mfa, idToken: ctx.secrets.encrypt(s.idToken), createdAt: now, lastSeenAt: now, expiresAt, absoluteExpiresAt },
|
||||
});
|
||||
res.cookie(SESSION_COOKIE, token, { ...cookieOptions(ctx), expires: expiresAt });
|
||||
}
|
||||
|
||||
export type Signed = {
|
||||
sessionId: string;
|
||||
idToken: string | null;
|
||||
mfa: boolean;
|
||||
member: { id: string; name: string; email: string; roles: AppRole[] };
|
||||
/** The roles this sign-in may use: all of them with 2FA, none without (§2). */
|
||||
activeRoles: AppRole[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The signed-in member for this request, or null. With `res`, a visit renews the session (and its
|
||||
* cookie) for another `sessionDays`, up to the absolute limit, and counts the member as active today.
|
||||
*/
|
||||
export async function currentSession(ctx: Ctx, req: Request, res?: Response): Promise<Signed | null> {
|
||||
const token = readCookies(req)[SESSION_COOKIE];
|
||||
if (!token) return null;
|
||||
const session = await ctx.db.session.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
if (!session) return null;
|
||||
const now = ctx.now();
|
||||
if (session.expiresAt <= now) {
|
||||
await ctx.db.session.delete({ where: { id: session.id } }).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
const member = await ctx.db.member.findUnique({ where: { id: session.memberId } });
|
||||
if (!member) return null;
|
||||
if (res && now.getTime() - session.lastSeenAt.getTime() > RENEW_EVERY_MS) {
|
||||
const expiresAt = rollingExpiry(now, session.absoluteExpiresAt, ctx.config.sessionDays);
|
||||
await ctx.db.session.update({ where: { id: session.id }, data: { lastSeenAt: now, expiresAt } }).catch(() => {});
|
||||
res.cookie(SESSION_COOKIE, token, { ...cookieOptions(ctx), expires: expiresAt });
|
||||
}
|
||||
if (res) await recordActive(ctx, member);
|
||||
let idToken: string | null;
|
||||
try {
|
||||
idToken = session.idToken ? ctx.secrets.decrypt(session.idToken) : null;
|
||||
} catch {
|
||||
idToken = null;
|
||||
}
|
||||
return {
|
||||
sessionId: session.id,
|
||||
idToken,
|
||||
mfa: session.mfa,
|
||||
member: { id: member.id, name: member.name, email: member.email, roles: member.roles },
|
||||
activeRoles: session.mfa ? member.roles : [],
|
||||
};
|
||||
}
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
signed?: Signed;
|
||||
}
|
||||
}
|
||||
|
||||
/** Any signed-in member (401 when signed out). Renews the session. */
|
||||
export function requireMember(ctx: Ctx): RequestHandler {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
currentSession(ctx, req, res).then((s) => {
|
||||
if (!s) return next(new ApiError(401, 'SIGNED_OUT', 'Please sign in.'));
|
||||
req.signed = s;
|
||||
return next();
|
||||
}).catch(next);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Someone with one of `roles` (or Owner / Church admin), signed in with 2FA. 401 when signed out,
|
||||
* 403 `TWO_FACTOR_NEEDED` when the role is there but this sign-in had no second step, 403
|
||||
* `FORBIDDEN` when the role isn't.
|
||||
*/
|
||||
export function requireRole(ctx: Ctx, roles: readonly AppRole[] = ROLES): RequestHandler {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
currentSession(ctx, req, res).then((s) => {
|
||||
if (!s) return next(new ApiError(401, 'SIGNED_OUT', 'Please sign in.'));
|
||||
if (!hasRole(s.member.roles, roles)) return next(new ApiError(403, 'FORBIDDEN', 'Your role in the App can\'t do that.'));
|
||||
if (!s.mfa) return next(new ApiError(403, 'TWO_FACTOR_NEEDED', 'Sign in again with your second step (two-factor) to use the admin.'));
|
||||
req.signed = s;
|
||||
return next();
|
||||
}).catch(next);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* The App's colours from the church's two (APP-1.0-PLAN §2), as the Website's palette
|
||||
* (WEBSITE-1.0-PLAN §3, "Colours from the church, made safe"): tints and shades, the text colour on
|
||||
* each, all checked against WCAG AA (4.5:1 for text). A colour that fails is darkened (or
|
||||
* lightened) until it passes, and the admin is told why.
|
||||
*/
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
const AA = 4.5;
|
||||
const WHITE: Rgb = [255, 255, 255];
|
||||
const INK: Rgb = [17, 24, 39];
|
||||
|
||||
export function hexToRgb(hex: string): Rgb {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
const n = parseInt(m ? m[1]! : '1f4e79', 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
|
||||
export const rgbToHex = (c: Rgb) => `#${c.map((x) => Math.round(x).toString(16).padStart(2, '0')).join('')}`;
|
||||
|
||||
/** "31 78 121": for Tailwind's `rgb(var(--brand) / <alpha-value>)`. */
|
||||
export const triple = (c: Rgb) => c.map((x) => Math.round(x)).join(' ');
|
||||
|
||||
function luminance([r, g, b]: Rgb): number {
|
||||
const lin = (v: number) => {
|
||||
const s = v / 255;
|
||||
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
||||
}
|
||||
|
||||
export function contrast(a: Rgb, b: Rgb): number {
|
||||
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number];
|
||||
return (x + 0.05) / (y + 0.05);
|
||||
}
|
||||
|
||||
/** `c` mixed with `to` by `t` (0 = c, 1 = to). */
|
||||
export const mix = (c: Rgb, to: Rgb, t: number): Rgb => [0, 1, 2].map((i) => c[i]! + (to[i]! - c[i]!) * t) as Rgb;
|
||||
|
||||
/** The nearest shade of `c` (towards black) that reaches `ratio` against `against`. */
|
||||
function darkenUntil(c: Rgb, against: Rgb, ratio = AA): Rgb {
|
||||
for (let t = 0; t <= 1; t += 0.02) {
|
||||
const d = mix(c, [0, 0, 0], t);
|
||||
if (contrast(d, against) >= ratio) return d;
|
||||
}
|
||||
return [0, 0, 0];
|
||||
}
|
||||
|
||||
export type Palette = {
|
||||
/** The church's colour as a background (buttons, bands), with `onBrand` text on it. */
|
||||
brand: string;
|
||||
brandDark: string;
|
||||
onBrand: string;
|
||||
/** The church's colour as text or a link on white: darkened when it's too light to read. */
|
||||
brandText: string;
|
||||
/** A soft background in the church's colour (cards and the tab bar). */
|
||||
brandTint: string;
|
||||
accent: string;
|
||||
onAccent: string;
|
||||
/** What was changed and why, for the admin (§3: "the admin is told why"). */
|
||||
notes: string[];
|
||||
};
|
||||
|
||||
export function buildPalette(primaryHex: string, accentHex: string | null): Palette {
|
||||
const notes: string[] = [];
|
||||
const primary = hexToRgb(primaryHex);
|
||||
const accent = accentHex ? hexToRgb(accentHex) : mix(primary, WHITE, 0.25);
|
||||
|
||||
// Text on the brand colour: white when it reads, else dark ink; if neither reaches AA, the
|
||||
// background is darkened until white does.
|
||||
let brand = primary;
|
||||
let onBrand = contrast(WHITE, brand) >= AA ? WHITE : contrast(INK, brand) >= AA ? INK : null;
|
||||
if (!onBrand) {
|
||||
brand = darkenUntil(primary, WHITE);
|
||||
onBrand = WHITE;
|
||||
notes.push(`Your main colour ${rgbToHex(primary)} is darkened to ${rgbToHex(brand)} behind text, so the text on buttons and bands can be read.`);
|
||||
}
|
||||
|
||||
const brandTextRgb = contrast(primary, WHITE) >= AA ? primary : darkenUntil(primary, WHITE);
|
||||
if (brandTextRgb !== primary) notes.push(`Links and headings in your main colour use a darker shade (${rgbToHex(brandTextRgb)}), so they can be read on white.`);
|
||||
|
||||
const onAccent = contrast(WHITE, accent) >= AA ? WHITE : INK;
|
||||
if (contrast(onAccent, accent) < AA) notes.push(`Your accent colour ${rgbToHex(accent)} is only used for decoration: text on it would be hard to read.`);
|
||||
|
||||
return {
|
||||
brand: triple(brand),
|
||||
brandDark: triple(mix(brand, [0, 0, 0], 0.2)),
|
||||
onBrand: triple(onBrand),
|
||||
brandText: triple(brandTextRgb),
|
||||
brandTint: triple(mix(primary, WHITE, 0.92)),
|
||||
accent: triple(accent),
|
||||
onAccent: triple(onAccent),
|
||||
notes,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The church profile (`crosscode.church/1`) from the church's Accounts (APP-1.0-PLAN §9): name,
|
||||
* short name, logo, icon, colours, brand style, timezone, contact, the church's other sites.
|
||||
* Accounts owns it; the App shows it and never stores it (P16: shared facts are edited in Accounts).
|
||||
* As the Website's church/profile.ts: kept in memory for 10 minutes, the last copy kept while
|
||||
* Accounts can't be reached (tried again after a minute).
|
||||
*
|
||||
* Before the App is linked to Accounts (and in local development) the profile saved in AppSetting
|
||||
* `church_profile_local` is used, if any (the demo saves the demo church's).
|
||||
*/
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { accountsLink } from '../auth/accounts.js';
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
|
||||
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
const caches = new WeakMap<Ctx, { cached: Cached | null; pending: Promise<Church | null> | null }>();
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
const parsed = churchSchema.safeParse(await res.json());
|
||||
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function localProfile(ctx: Ctx): Promise<Church | null> {
|
||||
const raw = await ctx.settings.json<unknown>('church_profile_local', null);
|
||||
const parsed = raw ? churchSchema.safeParse(raw) : null;
|
||||
return parsed?.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** The church's profile, or null when there's none yet. Never throws. */
|
||||
export async function churchProfile(ctx: Ctx): Promise<Church | null> {
|
||||
let link;
|
||||
try {
|
||||
link = await accountsLink(ctx);
|
||||
} catch {
|
||||
link = null;
|
||||
}
|
||||
if (!link) return localProfile(ctx).catch(() => null);
|
||||
let state = caches.get(ctx);
|
||||
if (!state) caches.set(ctx, (state = { cached: null, pending: null }));
|
||||
const { cached } = state;
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && ctx.now().getTime() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!state.pending) {
|
||||
const last = cached?.url === url ? cached.church : null;
|
||||
const s = state;
|
||||
s.pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
s.cached = { url, church, at: ctx.now().getTime(), ok: true };
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
s.cached = { url, church: last, at: ctx.now().getTime(), ok: false };
|
||||
return last;
|
||||
})
|
||||
.finally(() => { s.pending = null; });
|
||||
}
|
||||
return state.pending;
|
||||
}
|
||||
|
||||
/** `church.changed` from Accounts: fetched again next time (the last copy is shown meanwhile). */
|
||||
export function churchChanged(ctx: Ctx): void {
|
||||
const state = caches.get(ctx);
|
||||
if (state?.cached) state.cached = { ...state.cached, at: 0 };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
|
||||
* whole app against an in-memory database and a stand-in Accounts (tests/support/).
|
||||
*/
|
||||
import type { PrismaClient } from './generated/prisma/client.js';
|
||||
import type { Config } from './lib/config.js';
|
||||
import { Secrets } from './lib/crypto.js';
|
||||
import { Settings } from './lib/settings.js';
|
||||
import { loadAuthClient, type AuthClientModule } from './auth/accounts.js';
|
||||
|
||||
export type Db = PrismaClient;
|
||||
|
||||
export type Ctx = {
|
||||
config: Config;
|
||||
db: Db;
|
||||
secrets: Secrets;
|
||||
settings: Settings;
|
||||
/** `@crosscode/auth-client` (tests give a stand-in). */
|
||||
authClient: () => Promise<AuthClientModule>;
|
||||
now: () => Date;
|
||||
};
|
||||
|
||||
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule> } = {}): Ctx {
|
||||
const secrets = new Secrets(config.secret);
|
||||
const partial = { config, db, secrets } as Ctx;
|
||||
partial.settings = new Settings(partial);
|
||||
partial.authClient = opts.authClient ?? loadAuthClient;
|
||||
partial.now = opts.now ?? (() => new Date());
|
||||
return partial;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
|
||||
* Events' /api/v2), async handlers, and a same-origin check on everything that changes something.
|
||||
*/
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Known errors carry a status and code; anything else is a 500. */
|
||||
export function sendError(res: Response, e: unknown) {
|
||||
if (e instanceof ApiError) {
|
||||
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
|
||||
}
|
||||
console.error('[api]', e);
|
||||
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
||||
}
|
||||
|
||||
/** A handler whose result is sent as JSON; an error (thrown or rejected) as `{ error }`. */
|
||||
export const handle = (fn: (req: Request, res: Response) => unknown): RequestHandler => (req, res) => {
|
||||
Promise.resolve().then(() => fn(req, res)).then((out) => {
|
||||
if (out !== undefined && !res.headersSent) res.json(out);
|
||||
}).catch((e) => sendError(res, e));
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address, as
|
||||
* Accounts' http.ts. With SameSite=Lax cookies this stops another site posting on someone's behalf.
|
||||
*/
|
||||
export function sameOrigin(publicUrl: string, production: boolean): RequestHandler {
|
||||
const own = new URL(publicUrl).origin;
|
||||
return (req, res, next) => {
|
||||
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
||||
let origin = req.get('origin') ?? null;
|
||||
if (!origin && req.get('referer')) {
|
||||
try {
|
||||
origin = new URL(req.get('referer')!).origin;
|
||||
} catch {
|
||||
origin = null;
|
||||
}
|
||||
}
|
||||
if (origin === own || (!production && origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin))) return next();
|
||||
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* The App and the Hub (docs/hub-protocol.md §6, protocol v2, product `app`), as the Website's
|
||||
* hub/client.ts: register with a `CCP-` licence key (by itself from HUB_LICENCE_KEY on a Hub
|
||||
* install), then a signed heartbeat every 15 minutes with aggregate counts only
|
||||
* (`hub.appStatsSchema`): the active-member band the App tier is billed on (APP-1.0-PLAN §10), the
|
||||
* modules switched on, and counts. Never a name, a prayer request or anything a member wrote (§4).
|
||||
* The reply's `linkedProducts` (the church's other installs) is cached for Connect, and the App
|
||||
* connects itself to the church's Accounts once the Hub lists it (links/connect.ts).
|
||||
*
|
||||
* The install id the Hub gives is also the App's OIDC client id at Accounts.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import type { z } from 'zod';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
import { connectAccountsIfListed } from '../links/connect.js';
|
||||
import { keyPair, saveLinkedProducts } from '../links/store.js';
|
||||
import { activeMembers } from '../members/activity.js';
|
||||
import { enabledModules } from '../modules.js';
|
||||
import { hubPublicKey, verifyToken } from './licence.js';
|
||||
import { jobsHealth } from '../jobs.js';
|
||||
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
const TIMEOUT_MS = 15000;
|
||||
const STARTED_AT = Date.now();
|
||||
|
||||
export class HubError extends Error {
|
||||
constructor(message: string, public code: string, public status: number) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
|
||||
const raw = JSON.stringify(body);
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (sign) {
|
||||
const timestamp = ctx.now().toISOString();
|
||||
headers['X-Hub-Install'] = sign.installId;
|
||||
headers['X-Hub-Timestamp'] = timestamp;
|
||||
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
|
||||
}
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
} catch (e) {
|
||||
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function dbUp(ctx: Ctx): Promise<boolean> {
|
||||
try {
|
||||
await ctx.db.$queryRaw`SELECT 1`;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function health(ctx: Ctx) {
|
||||
return {
|
||||
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||
db: await dbUp(ctx),
|
||||
jobs: await jobsHealth(ctx),
|
||||
// The nightly backup comes with the App's backups (as the Website's, before 1.0.0).
|
||||
lastBackupAt: null,
|
||||
disk: null,
|
||||
errorsLast24h: null,
|
||||
pendingMigrations: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate counts only (hub.appStatsSchema). Prayer coverage, commitments, announcements and
|
||||
* messages are 0 until their modules arrive.
|
||||
*/
|
||||
export async function stats(ctx: Ctx): Promise<z.infer<typeof hub.appStatsSchema>> {
|
||||
const [{ band }, modules] = await Promise.all([activeMembers(ctx), enabledModules(ctx)]);
|
||||
return {
|
||||
activeMembers90d: band,
|
||||
modules,
|
||||
prayer: { coverageLast7dPercent: 0, activeCommitments: 0 },
|
||||
announcements: { last30d: 0 },
|
||||
messages: { email30d: 0, whatsapp30d: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
/** Register with a licence key (HUB_LICENCE_KEY). */
|
||||
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
|
||||
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('APP_URL isn\'t set.', 'NO_SITE_URL', 400);
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
licenceKey: licenceKey.trim().toUpperCase(),
|
||||
product: 'app',
|
||||
install: {
|
||||
name: 'App',
|
||||
url: ctx.config.publicUrl,
|
||||
adminContact,
|
||||
version: appVersion(),
|
||||
timezone: ctx.config.timezone,
|
||||
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
|
||||
features: {},
|
||||
publicKey: publicKeyPem,
|
||||
},
|
||||
};
|
||||
const check = hub.registerRequestSchema.safeParse(body);
|
||||
if (!check.success) throw new HubError('That doesn\'t look like a Church App licence key (CCP-…).', 'INVALID_REQUEST', 400);
|
||||
const data = await post(ctx, '/api/installs/register', check.data);
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: String(data.installId),
|
||||
hub_install_secret: String(data.installSecret),
|
||||
hub_licence: String(data.licence),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
hub_public_key_status: 'matches',
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return claims;
|
||||
}
|
||||
|
||||
/** The heartbeat (every 15 minutes). Skips quietly when not connected. */
|
||||
export async function heartbeat(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
const secret = await ctx.settings.get('hub_install_secret');
|
||||
if (!installId || !secret) return { skipped: 'not connected' };
|
||||
const status = await ctx.settings.get('hub_public_key_status');
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
product: 'app',
|
||||
version: appVersion(),
|
||||
health: await health(ctx),
|
||||
stats: await stats(ctx),
|
||||
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
|
||||
};
|
||||
try {
|
||||
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
await ctx.settings.setMany({
|
||||
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
|
||||
if (err.code === 'INSTALL_NOT_FOUND') {
|
||||
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
|
||||
return { ok: false, reconnect: true };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY. Never throws. */
|
||||
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
|
||||
const key = ctx.config.hubLicenceKey;
|
||||
if (!key) return { connected: false, reason: 'no_key' };
|
||||
for (let i = 1; i <= attempts; i++) {
|
||||
try {
|
||||
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
|
||||
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
|
||||
return { connected: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
|
||||
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
|
||||
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
|
||||
}
|
||||
}
|
||||
return { connected: false, reason: 'unreachable' };
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
|
||||
* key, as Cross Events does. A lapsed licence never takes the public site down (the Hub is never on the runtime path,
|
||||
* ROADMAP-v3 §1): admins see a banner.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
|
||||
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
|
||||
export function normalisePem(input: string | null | undefined): string | null {
|
||||
const text = String(input || '').replace(/\\n/g, '\n').trim();
|
||||
if (!text) return null;
|
||||
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
|
||||
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
|
||||
}
|
||||
|
||||
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
|
||||
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
export type LicenceClaims = {
|
||||
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
|
||||
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
|
||||
};
|
||||
|
||||
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
|
||||
if (!pem) return null;
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
|
||||
try {
|
||||
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
|
||||
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
|
||||
|
||||
/** The state for verified claims. Pure. */
|
||||
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
|
||||
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
|
||||
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
|
||||
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
|
||||
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
|
||||
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
|
||||
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
|
||||
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
|
||||
return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
}
|
||||
|
||||
export async function licenceStatus(ctx: Ctx) {
|
||||
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
|
||||
const claims = verifyToken(token, hubPublicKey(ctx));
|
||||
const valid = claims && claims.installId === installId ? claims : null;
|
||||
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
|
||||
}
|
||||
|
||||
/** The church's Hub customer id (the same for every product), once the licence says it. */
|
||||
export async function customerId(ctx: Ctx): Promise<string | null> {
|
||||
return (await licenceStatus(ctx)).claims?.customerId ?? null;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Starts the Church App's backend: database, HTTP server, and (on a Hub install) registering with
|
||||
* the Hub from HUB_LICENCE_KEY, then the background jobs (src/jobs.ts): the heartbeat, which also
|
||||
* links the App to the church's Accounts once the Hub lists it.
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from './generated/prisma/client.js';
|
||||
import { createApp } from './app.js';
|
||||
import { createCtx } from './context.js';
|
||||
import { connectFromEnv, heartbeat } from './hub/client.js';
|
||||
import { startJobs } from './jobs.js';
|
||||
import { loadConfig } from './lib/config.js';
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig();
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set.');
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
|
||||
const ctx = createCtx(config, db);
|
||||
const app = createApp(ctx);
|
||||
const server = app.listen(config.port, () => console.log(`[app] Listening on ${config.port} (${config.publicUrl}).`));
|
||||
const stopJobs = await startJobs(ctx, url);
|
||||
|
||||
connectFromEnv(ctx).then((r) => {
|
||||
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
|
||||
}).catch(() => {});
|
||||
|
||||
const stop = async () => {
|
||||
await stopJobs();
|
||||
server.close();
|
||||
await db.$disconnect();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
process.on('SIGINT', stop);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('[app] Failed to start:', e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,302 @@
|
||||
/**
|
||||
* Background jobs on pg-boss (as the Website, Accounts and Cross Events): one run per schedule
|
||||
* however many processes run, and timers in this process if the queue can't start.
|
||||
* JOBS_ENABLED=false turns them all off.
|
||||
*
|
||||
* So far only the Hub heartbeat. The modules add theirs (APP-1.0-PLAN §1): reminders, renewals,
|
||||
* the event feed, Cross Code's devotionals (the next 2 weeks, today included, once a night, §6),
|
||||
* announcement and devotional sends, and the nightly backup.
|
||||
*
|
||||
* Settings → Background jobs (§10) shows each job's schedule and last runs, runs one now, and
|
||||
* switches one on or off or changes its schedule. That choice is kept in the database
|
||||
* (`job_overrides`), wins over the .env (a job's own flag and JOB_SCHEDULE_<NAME>) and takes effect
|
||||
* straight away (in other processes within 30 seconds).
|
||||
*/
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import PgBoss from 'pg-boss';
|
||||
import type { Ctx } from './context.js';
|
||||
import { heartbeat } from './hub/client.js';
|
||||
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
export const JOBS: Job[] = [
|
||||
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
|
||||
];
|
||||
|
||||
const SCHEMA = 'pgboss_app';
|
||||
const OVERRIDES_KEY = 'job_overrides';
|
||||
const OVERRIDES_TTL_MS = 30_000;
|
||||
|
||||
export type Override = { enabled?: boolean; cron?: string };
|
||||
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
|
||||
|
||||
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
|
||||
type State = {
|
||||
mode: 'queue' | 'timers' | 'off';
|
||||
boss: PgBoss | null;
|
||||
timers: Map<string, NodeJS.Timeout>;
|
||||
history: Map<string, Run[]>;
|
||||
overrides: Record<string, Override>;
|
||||
overridesAt: number;
|
||||
env: NodeJS.ProcessEnv;
|
||||
};
|
||||
|
||||
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
|
||||
|
||||
/** Tests: a different environment for the env flags and schedules. */
|
||||
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
|
||||
state.env = env;
|
||||
}
|
||||
|
||||
const flag = (name: string | null) => {
|
||||
if (!name) return true;
|
||||
const v = state.env[name];
|
||||
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
|
||||
};
|
||||
|
||||
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
|
||||
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
|
||||
try {
|
||||
CronExpressionParser.parse(cron, { tz });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
|
||||
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
|
||||
try {
|
||||
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
|
||||
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
|
||||
const parsed = row?.value ? JSON.parse(row.value) : {};
|
||||
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
state.overridesAt = Date.now();
|
||||
} catch (e) {
|
||||
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
|
||||
}
|
||||
return state.overrides;
|
||||
}
|
||||
|
||||
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
|
||||
export const envEnabled = (job: Job) => flag(job.env);
|
||||
|
||||
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
|
||||
export function isEnabled(ctx: Ctx, job: Job): boolean {
|
||||
if (!ctx.config.jobsEnabled) return false;
|
||||
const o = state.overrides[job.name];
|
||||
if (o && typeof o.enabled === 'boolean') return o.enabled;
|
||||
return envEnabled(job);
|
||||
}
|
||||
|
||||
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
|
||||
export function envCronFor(ctx: Ctx, job: Job): string {
|
||||
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
|
||||
if (v && isCron(v, ctx.config.timezone)) return v;
|
||||
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
|
||||
return job.cron;
|
||||
}
|
||||
|
||||
export function cronFor(ctx: Ctx, job: Job): string {
|
||||
const o = state.overrides[job.name];
|
||||
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
|
||||
return envCronFor(ctx, job);
|
||||
}
|
||||
|
||||
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
|
||||
|
||||
function remember(name: string, run: Run) {
|
||||
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
|
||||
}
|
||||
|
||||
async function runJob(ctx: Ctx, job: Job) {
|
||||
return (await job.run(ctx)) ?? null;
|
||||
}
|
||||
|
||||
function startTimer(ctx: Ctx, job: Job) {
|
||||
const tz = ctx.config.timezone;
|
||||
const scheduleNext = () => {
|
||||
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
|
||||
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
|
||||
state.timers.set(job.name, setTimeout(async () => {
|
||||
await loadOverrides(ctx);
|
||||
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
|
||||
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
||||
try {
|
||||
entry.output = await runJob(ctx, job);
|
||||
entry.state = 'completed';
|
||||
} catch (e) {
|
||||
entry.state = 'failed';
|
||||
entry.output = { message: (e as Error).message };
|
||||
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
|
||||
} finally {
|
||||
entry.completedOn = new Date();
|
||||
remember(job.name, entry);
|
||||
scheduleNext();
|
||||
}
|
||||
}, Math.min(delay, 2 ** 31 - 1)));
|
||||
};
|
||||
scheduleNext();
|
||||
}
|
||||
|
||||
async function applyJob(ctx: Ctx, job: Job) {
|
||||
if (state.mode === 'queue' && state.boss) {
|
||||
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
|
||||
else await state.boss.unschedule(job.name).catch(() => {});
|
||||
} else if (state.mode === 'timers') {
|
||||
clearTimeout(state.timers.get(job.name));
|
||||
state.timers.delete(job.name);
|
||||
startTimer(ctx, job);
|
||||
}
|
||||
}
|
||||
|
||||
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
|
||||
if (!ctx.config.jobsEnabled) {
|
||||
state.mode = 'off';
|
||||
return async () => {};
|
||||
}
|
||||
await loadOverrides(ctx, true);
|
||||
const tz = ctx.config.timezone;
|
||||
try {
|
||||
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-app-jobs' });
|
||||
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
|
||||
await boss.start();
|
||||
state.boss = boss;
|
||||
state.mode = 'queue';
|
||||
for (const job of JOBS) {
|
||||
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
|
||||
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
|
||||
await boss.work(job.name, async (batch) => {
|
||||
await loadOverrides(ctx);
|
||||
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
|
||||
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
|
||||
return runJob(ctx, job);
|
||||
});
|
||||
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
|
||||
else await boss.unschedule(job.name).catch(() => {});
|
||||
}
|
||||
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
|
||||
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
|
||||
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
|
||||
} catch (e) {
|
||||
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
|
||||
state.boss = null;
|
||||
state.mode = 'timers';
|
||||
for (const job of JOBS) startTimer(ctx, job);
|
||||
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
|
||||
}
|
||||
}
|
||||
|
||||
export class JobError extends Error {
|
||||
constructor(public status: number, message: string) { super(message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
|
||||
* .env, null goes back to it, undefined leaves it.
|
||||
*/
|
||||
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
|
||||
const job = JOBS.find((j) => j.name === name);
|
||||
if (!job) throw new JobError(404, 'There\'s no such job.');
|
||||
const { enabled, cron } = change;
|
||||
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
|
||||
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
|
||||
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
|
||||
}
|
||||
const all = { ...(await loadOverrides(ctx, true)) };
|
||||
const entry: Override = { ...(all[name] ?? {}) };
|
||||
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
|
||||
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
|
||||
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
|
||||
const value = JSON.stringify(all);
|
||||
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
|
||||
ctx.settings.forget();
|
||||
state.overrides = all;
|
||||
state.overridesAt = Date.now();
|
||||
await applyJob(ctx, job);
|
||||
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
|
||||
}
|
||||
|
||||
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
|
||||
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
|
||||
const job = JOBS.find((j) => j.name === name);
|
||||
if (!job) throw new JobError(404, 'There\'s no such job.');
|
||||
if (state.mode === 'queue' && state.boss) {
|
||||
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
|
||||
return { queued: true };
|
||||
}
|
||||
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
|
||||
try {
|
||||
entry.output = await runJob(ctx, job);
|
||||
entry.state = 'completed';
|
||||
return { queued: false, output: entry.output };
|
||||
} catch (e) {
|
||||
entry.state = 'failed';
|
||||
entry.output = { message: (e as Error).message };
|
||||
throw new JobError(502, `The job failed: ${(e as Error).message}`);
|
||||
} finally {
|
||||
entry.completedOn = new Date();
|
||||
remember(job.name, entry);
|
||||
}
|
||||
}
|
||||
|
||||
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
|
||||
export async function jobStatus(ctx: Ctx) {
|
||||
await loadOverrides(ctx, true);
|
||||
const tz = ctx.config.timezone;
|
||||
const recent = new Map<string, Run[]>();
|
||||
if (state.mode === 'queue') {
|
||||
try {
|
||||
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
|
||||
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
|
||||
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
|
||||
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
|
||||
FROM (
|
||||
SELECT name, state::text, created_on, started_on, completed_on, output,
|
||||
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
|
||||
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
|
||||
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
|
||||
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
|
||||
} catch (e) {
|
||||
console.warn('[jobs] Could not read the run history:', (e as Error).message);
|
||||
}
|
||||
} else {
|
||||
for (const [name, list] of state.history) recent.set(name, list);
|
||||
}
|
||||
return {
|
||||
mode: state.mode,
|
||||
timezone: tz,
|
||||
jobsEnabledEnv: ctx.config.jobsEnabled,
|
||||
jobs: JOBS.map((job) => {
|
||||
const cron = cronFor(ctx, job);
|
||||
const enabled = isEnabled(ctx, job);
|
||||
const o = state.overrides[job.name] ?? {};
|
||||
return {
|
||||
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
|
||||
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
|
||||
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
|
||||
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
|
||||
recent: recent.get(job.name) ?? [],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** What the Hub's heartbeat reports (hub.healthSchema `jobs`): the real mode and failed runs in 24 hours. */
|
||||
export async function jobsHealth(ctx: Ctx): Promise<{ mode: 'queue' | 'timers' | 'off'; failedLast24h: number }> {
|
||||
const since = ctx.now().getTime() - 24 * 3600e3;
|
||||
if (state.mode === 'queue') {
|
||||
try {
|
||||
const rows = await ctx.db.$queryRawUnsafe<{ n: number | bigint }[]>(
|
||||
`SELECT count(*)::int AS n FROM ${SCHEMA}.job WHERE state = 'failed' AND name = ANY($1::text[]) AND completed_on > now() - interval '24 hours'`,
|
||||
JOBS.map((j) => j.name),
|
||||
);
|
||||
return { mode: 'queue', failedLast24h: Number(rows[0]?.n ?? 0) };
|
||||
} catch {
|
||||
return { mode: 'queue', failedLast24h: 0 };
|
||||
}
|
||||
}
|
||||
let failed = 0;
|
||||
for (const runs of state.history.values()) failed += runs.filter((r) => r.state === 'failed' && (r.completedOn?.getTime() ?? 0) > since).length;
|
||||
return { mode: state.mode, failedLast24h: failed };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The admin audit log (who changed what, APP-1.0-PLAN §10). Logging never breaks the
|
||||
* action it records.
|
||||
*/
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export function clientIp(req: Request | undefined): string | null {
|
||||
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
|
||||
}
|
||||
|
||||
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
|
||||
try {
|
||||
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
|
||||
} catch (e) {
|
||||
console.error('[audit]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
|
||||
* tests pass their own with `loadConfig({...})`.
|
||||
*/
|
||||
export type TrustProxy = false | number | string | string[];
|
||||
|
||||
export type Config = {
|
||||
/** The public address, e.g. https://app.acaciahill.co.za (no trailing slash). */
|
||||
publicUrl: string;
|
||||
port: number;
|
||||
/** Signs cookies and links, encrypts stored secrets. Generated on the server, never sent anywhere. */
|
||||
secret: string;
|
||||
production: boolean;
|
||||
/** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */
|
||||
trustProxySetting: TrustProxy;
|
||||
hubUrl: string;
|
||||
hubLicenceKey: string | null;
|
||||
hubPublicKey: string | null;
|
||||
/** The church's contact from the Hub: the first person to sign in with this (verified) email becomes the Owner. */
|
||||
hubAdminName: string | null;
|
||||
hubAdminEmail: string | null;
|
||||
/** Until the church profile says otherwise (the profile's timezone wins, §1). */
|
||||
timezone: string;
|
||||
jobsEnabled: boolean;
|
||||
/** Local testing only: linked products (Accounts) on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
/** A sign-in lasts this many days, renewed by each visit (decision 7: 8). */
|
||||
sessionDays: number;
|
||||
/** ... up to this many days from the sign-in (decision 7: 90). */
|
||||
sessionMaxDays: number;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
|
||||
/** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */
|
||||
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
|
||||
const raw = (v ?? '').trim();
|
||||
if (raw === '') return production ? 1 : false;
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'true') return 1;
|
||||
if (lower === 'false') return false;
|
||||
if (/^\d+$/.test(raw)) return Number(raw) || false;
|
||||
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
|
||||
}
|
||||
|
||||
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||
const production = env.NODE_ENV === 'production';
|
||||
const secret = env.APP_SECRET || '';
|
||||
if (production && secret.length < 32) throw new Error('APP_SECRET must be set (at least 32 characters) in production.');
|
||||
const sessionMaxDays = Math.min(365, Math.max(1, Number(env.SESSION_MAX_DAYS) || 90));
|
||||
return {
|
||||
publicUrl: String(env.APP_URL || 'http://localhost:3400').replace(/\/+$/, ''),
|
||||
port: Number(env.PORT || 5400),
|
||||
secret: secret || 'development-only-secret-change-me-0123456789',
|
||||
production,
|
||||
trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production),
|
||||
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
|
||||
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
|
||||
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
|
||||
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
|
||||
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim().toLowerCase() || null,
|
||||
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
sessionDays: Math.min(sessionMaxDays, Math.max(1, Number(env.SESSION_DAYS) || 8)),
|
||||
sessionMaxDays,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Secrets at rest (AES-256-GCM, as Accounts' and the Website's lib/crypto.ts), and tokens. The key
|
||||
* comes from APP_SECRET; encrypted values start with "enc:".
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const SENTINEL = 'enc:';
|
||||
|
||||
export class Secrets {
|
||||
private readonly key: Buffer;
|
||||
|
||||
constructor(secret: string) {
|
||||
this.key = crypto.scryptSync(secret, 'crosscode-app-aes256gcm-v1', 32);
|
||||
}
|
||||
|
||||
encrypt(plain: string): string {
|
||||
if (plain.startsWith(SENTINEL)) return plain;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
|
||||
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
|
||||
}
|
||||
|
||||
/** Throws if the value was changed or encrypted with another key. */
|
||||
decrypt(value: string): string {
|
||||
if (!value.startsWith(SENTINEL)) return value;
|
||||
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
|
||||
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/** A random token for a cookie (32 bytes, base64url). */
|
||||
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
/** What's stored for a token: only its SHA-256. */
|
||||
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Site settings in `AppSetting` (key → string), as Accounts' lib/settings.ts. Secret ones are
|
||||
* encrypted at rest and never sent to the browser. A short cache keeps pages from reading the
|
||||
* table on every request.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']);
|
||||
|
||||
const TTL_MS = 30_000;
|
||||
|
||||
export class Settings {
|
||||
private cache = new Map<string, { value: string | null; at: number }>();
|
||||
|
||||
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
const hit = this.cache.get(key);
|
||||
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
||||
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
|
||||
let value = row?.value ?? null;
|
||||
if (value !== null && SECRET_SETTINGS.has(key)) {
|
||||
try {
|
||||
value = this.ctx.secrets.decrypt(value);
|
||||
} catch {
|
||||
value = null;
|
||||
}
|
||||
}
|
||||
this.cache.set(key, { value, at: Date.now() });
|
||||
return value;
|
||||
}
|
||||
|
||||
async bool(key: string, fallback: boolean): Promise<boolean> {
|
||||
const v = await this.get(key);
|
||||
return v === null || v === '' ? fallback : v === 'true';
|
||||
}
|
||||
|
||||
async json<T>(key: string, fallback: T): Promise<T> {
|
||||
const v = await this.get(key);
|
||||
if (!v) return fallback;
|
||||
try {
|
||||
return JSON.parse(v) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
|
||||
else {
|
||||
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
|
||||
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
|
||||
}
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
async setMany(values: Record<string, string | null>): Promise<void> {
|
||||
for (const [k, v] of Object.entries(values)) await this.set(k, v);
|
||||
}
|
||||
|
||||
forget(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
|
||||
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
|
||||
* however the process was started (PM2 doesn't set npm_package_version).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
let cached: string | null = null;
|
||||
|
||||
export function appVersion(): string {
|
||||
if (!cached) {
|
||||
try {
|
||||
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
||||
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
|
||||
} catch {
|
||||
cached = '0.0.0';
|
||||
}
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4, Accounts and the Website). The
|
||||
* App links to the church's **Accounts** (signing in: the link's secret is where the client secret
|
||||
* comes from, and Accounts registers the App as an OIDC client when it accepts; later also the
|
||||
* shared email and WhatsApp settings, APP-1.0-PLAN §8) and, for the event feed (§7), to **Events**
|
||||
* and the **Website**.
|
||||
*
|
||||
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in this
|
||||
* site's cached `linkedProducts` (same church), signed with the key the Hub listed for it.
|
||||
*/
|
||||
import {
|
||||
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
|
||||
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
|
||||
} from '@crosscode/contracts';
|
||||
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { callSibling, LinkCallError, siblingUrl } from './http.js';
|
||||
import { keyPair, linkedProducts, listedProduct } from './store.js';
|
||||
|
||||
export class LinkError extends Error {
|
||||
constructor(message: string, public code: string, public status = 400) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The products the App links to. */
|
||||
const LINKABLE = new Set(['accounts', 'events', 'website']);
|
||||
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||
const REFRESH_EVERY_MS = 60 * 1000;
|
||||
const SIGN_IN_TRY_EVERY_MS = 15 * 1000;
|
||||
|
||||
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
|
||||
|
||||
/**
|
||||
* A fresh list of the church's products from the Hub (a heartbeat), at most once a minute,
|
||||
* so a message from an unknown install can't make the App call the Hub more often than that.
|
||||
* Several callers inside that minute share one heartbeat. Never throws.
|
||||
*/
|
||||
async function refreshList(ctx: Ctx): Promise<void> {
|
||||
const now = ctx.now().getTime();
|
||||
let r = refreshes.get(ctx);
|
||||
if (!r || now - r.at >= REFRESH_EVERY_MS) {
|
||||
// Imported here: hub/client.ts imports this file (it links to Accounts after each heartbeat).
|
||||
r = { at: now, run: import('../hub/client.js').then((m) => m.heartbeat(ctx)).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
|
||||
refreshes.set(ctx, r);
|
||||
}
|
||||
await r.run;
|
||||
}
|
||||
|
||||
/**
|
||||
* The install as the Hub listed it. If the cached list doesn't have it yet (it was installed
|
||||
* after this site's last heartbeat), the App asks the Hub for a fresh list and looks again.
|
||||
*/
|
||||
async function listedOrRefreshed(ctx: Ctx, installId: string) {
|
||||
const found = await listedProduct(ctx, installId);
|
||||
if (found) return found;
|
||||
await refreshList(ctx);
|
||||
return listedProduct(ctx, installId);
|
||||
}
|
||||
|
||||
type Actor = { id: string | null; role: string };
|
||||
|
||||
async function self(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
if (!installId) throw new LinkError('The App isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
|
||||
const { privateKeyPem } = await keyPair(ctx);
|
||||
return { installId, url: ctx.config.publicUrl, privateKeyPem };
|
||||
}
|
||||
|
||||
const party = (s: { installId: string; url: string }) => ({ product: 'app' as const, installId: s.installId, url: s.url });
|
||||
|
||||
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
|
||||
const now = ctx.now();
|
||||
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||
try {
|
||||
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if ((e as { code?: string }).code === 'P2002') return false;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
|
||||
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById, lastSyncError: null };
|
||||
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||
}
|
||||
|
||||
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: Actor | null, req: Request | undefined, by: string) =>
|
||||
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
|
||||
|
||||
/** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */
|
||||
export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const sibling = await listedOrRefreshed(ctx, installId);
|
||||
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
|
||||
const me = await self(ctx);
|
||||
const secret = newLinkSecret();
|
||||
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
let reply: unknown;
|
||||
try {
|
||||
reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
|
||||
} catch (e) {
|
||||
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
|
||||
throw e;
|
||||
}
|
||||
const parsed = linkConnectedSchema.safeParse(reply);
|
||||
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
|
||||
const r: LinkConnected = parsed.data;
|
||||
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() }).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
|
||||
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
|
||||
}
|
||||
const link = await saveLink(ctx, sibling, secret, actor.id);
|
||||
await logLink(ctx, 'product_link_connected', link, actor, req, 'app');
|
||||
return link;
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/connect` (a sibling's admin pressed Connect there). */
|
||||
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise<LinkConnected> {
|
||||
const parsed = linkConnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const sibling = await listedOrRefreshed(ctx, m.from.installId);
|
||||
if (!sibling || sibling.product !== m.from.product || !LINKABLE.has(sibling.product)) {
|
||||
throw new LinkError('The Hub doesn\'t list that install for this church (the App asks it again at most once a minute).', 'NOT_LINKED', 403);
|
||||
}
|
||||
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
|
||||
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
const link = await saveLink(ctx, sibling, m.secret, null);
|
||||
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
|
||||
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
}
|
||||
|
||||
/** This site ends a link. The local link goes even if the sibling can't be reached. */
|
||||
export async function disconnectFrom(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId } });
|
||||
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||
let told = false;
|
||||
let problem: string | null = null;
|
||||
try {
|
||||
const me = await self(ctx);
|
||||
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
|
||||
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||
told = true;
|
||||
} catch (e) {
|
||||
problem = (e as Error).message;
|
||||
}
|
||||
await ctx.db.productLink.delete({ where: { installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'app');
|
||||
return { told, problem };
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
|
||||
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise<void> {
|
||||
const parsed = linkDisconnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||
if (!link) return;
|
||||
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
await ctx.db.productLink.delete({ where: { installId: link.installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
|
||||
}
|
||||
|
||||
/**
|
||||
* The App signs in through Accounts, so it connects to the church's Accounts by itself once the
|
||||
* Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat.
|
||||
* Never throws: a failure is tried again at the next heartbeat.
|
||||
*/
|
||||
export function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
|
||||
// One connect at a time (a heartbeat and a sign-in can both try): two at once would each
|
||||
// send Accounts a different secret, and the one each side kept last might not be the same.
|
||||
let run = connecting.get(ctx);
|
||||
if (!run) {
|
||||
run = connectAccountsOnce(ctx).finally(() => connecting.delete(ctx));
|
||||
connecting.set(ctx, run);
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
const connecting = new WeakMap<Ctx, Promise<'connected' | 'skipped' | 'failed'>>();
|
||||
|
||||
async function connectAccountsOnce(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
|
||||
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped';
|
||||
const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts');
|
||||
if (!listed) return 'skipped';
|
||||
try {
|
||||
await connectTo(ctx, listed.installId, { id: null, role: 'system' });
|
||||
return 'connected';
|
||||
} catch (e) {
|
||||
console.warn('[links] Connecting to Accounts failed:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
const signInTries = new WeakMap<Ctx, number>();
|
||||
|
||||
/**
|
||||
* Someone wants to sign in and there's no link to Accounts yet: link now instead of waiting
|
||||
* for the next heartbeat. If the cached list has no Accounts, the Hub is asked for a fresh one first
|
||||
* (which links by itself when it lists one). Tried at most every 15 seconds, so people pressing
|
||||
* Sign in can't make the App call Accounts or the Hub more often than that.
|
||||
*/
|
||||
export async function linkAccountsNow(ctx: Ctx): Promise<void> {
|
||||
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return;
|
||||
const now = ctx.now().getTime();
|
||||
const last = signInTries.get(ctx);
|
||||
if (last !== undefined && now - last < SIGN_IN_TRY_EVERY_MS) return;
|
||||
signInTries.set(ctx, now);
|
||||
if (!(await linkedProducts(ctx)).some((p) => p.product === 'accounts')) await refreshList(ctx);
|
||||
await connectAccountsIfListed(ctx);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
|
||||
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
|
||||
*/
|
||||
import dns from 'node:dns/promises';
|
||||
import net from 'node:net';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
const TIMEOUT_MS = 15000;
|
||||
const MAX_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export class LinkCallError extends Error {
|
||||
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function isPrivateAddress(ip: string): boolean {
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number) as [number, number];
|
||||
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
const v = ip.toLowerCase();
|
||||
if (v === '::1' || v === '::') return true;
|
||||
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
|
||||
if (mapped) return isPrivateAddress(mapped[1]!);
|
||||
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise<URL> {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
|
||||
} catch {
|
||||
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
|
||||
}
|
||||
const allow = ctx.config.allowPrivateLinks;
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||
if (!allow) {
|
||||
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
|
||||
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: init.method,
|
||||
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
|
||||
body: init.body,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE');
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||
const text = await res.text();
|
||||
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
|
||||
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* What the church's other products call (`crosscode.link/1` and friends), as the Website's
|
||||
* links/routes.ts. Errors use the link protocol's `{ code, message }`.
|
||||
*
|
||||
* POST /links/v1/connect, /disconnect a sibling connects or disconnects
|
||||
* POST /church/v1/changed Accounts: the church profile changed (signed)
|
||||
*
|
||||
* To come with their modules: the event feed (`/feed/v1/events`, `/feed/v1/changed`, §7) and
|
||||
* Accounts' "the messaging settings changed" (§8).
|
||||
*/
|
||||
import express from 'express';
|
||||
import { CHURCH_PATHS, churchChangedSchema, LINK_PATHS } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchChanged } from '../church/profile.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
|
||||
|
||||
export function linksRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
const json = express.json({ limit: '32kb' });
|
||||
const say = (res: express.Response, status: number, code: string, message: string) => res.status(status).json({ code, message });
|
||||
const fail = (res: express.Response, e: unknown) => {
|
||||
if (e instanceof LinkError) return say(res, e.status, e.code, e.message);
|
||||
console.error('[links]', e);
|
||||
return say(res, 500, 'INTERNAL', 'Something went wrong.');
|
||||
};
|
||||
|
||||
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
res.json(await acceptConnect(ctx, req.body, req));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
r.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
await acceptDisconnect(ctx, req.body, req);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
/** A signed message from a linked sibling: its link, or the reason it's refused. */
|
||||
async function signedBy(req: express.Request, res: express.Response, accountsOnly = false) {
|
||||
const sender = String(req.get(LINK_HEADERS.sender) || '');
|
||||
const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: sender } }) : null;
|
||||
if (!link || (accountsOnly && link.product !== 'accounts')) {
|
||||
say(res, 404, 'NOT_LINKED', 'The App has no link with that install.');
|
||||
return null;
|
||||
}
|
||||
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
|
||||
const check = verify({ secret: ctx.secrets.decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody, now: ctx.now() });
|
||||
if (!check.ok) {
|
||||
say(res, 401, check.code, 'The signature doesn\'t match this link.');
|
||||
return null;
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = JSON.parse(rawBody.toString('utf8'));
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
return { link, body };
|
||||
}
|
||||
|
||||
const raw = express.raw({ type: () => true, limit: '16kb' });
|
||||
|
||||
r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
|
||||
try {
|
||||
const got = await signedBy(req, res, true);
|
||||
if (!got) return undefined;
|
||||
if (!churchChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a church.changed message.');
|
||||
churchChanged(ctx);
|
||||
return res.status(202).json({ accepted: true });
|
||||
} catch (e) {
|
||||
return fail(res, e);
|
||||
}
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
|
||||
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
|
||||
* hub_linked_products.
|
||||
*/
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
type LinkedProduct = hub.LinkedProduct;
|
||||
|
||||
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
|
||||
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
|
||||
const pair = generateEd25519();
|
||||
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
|
||||
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||
}
|
||||
|
||||
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
|
||||
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
|
||||
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
|
||||
}
|
||||
|
||||
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
|
||||
if (!Array.isArray(list)) return;
|
||||
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
|
||||
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
|
||||
}
|
||||
|
||||
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
|
||||
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Active members (APP-1.0-PLAN §10, ROADMAP-v3 §10, billing): an account that used the App signed
|
||||
* in on any day in the last 90 days. The App writes the day at most once per member per day (in
|
||||
* the church's timezone) and reports only the band (`hub.activeMemberBand`) in the heartbeat.
|
||||
* Visitors browsing signed out never count.
|
||||
*/
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
const DAY = 24 * 3600e3;
|
||||
export const ACTIVE_DAYS = 90;
|
||||
|
||||
/** YYYY-MM-DD of `at` in `timezone`. */
|
||||
export const dayIn = (at: Date, timezone: string) =>
|
||||
new Intl.DateTimeFormat('en-CA', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(at);
|
||||
|
||||
/** Counts the member as active today, unless they already are. Never throws. */
|
||||
export async function recordActive(ctx: Ctx, member: { id: string; lastActiveAt: Date | null }): Promise<void> {
|
||||
const now = ctx.now();
|
||||
const tz = ctx.config.timezone;
|
||||
if (member.lastActiveAt && dayIn(member.lastActiveAt, tz) === dayIn(now, tz)) return;
|
||||
member.lastActiveAt = now;
|
||||
await ctx.db.member.update({ where: { id: member.id }, data: { lastActiveAt: now } }).catch(() => {});
|
||||
}
|
||||
|
||||
/** How many members used the App signed in during the last 90 days, and the band billed on. */
|
||||
export async function activeMembers(ctx: Ctx): Promise<{ count: number; band: (typeof hub.ACTIVE_MEMBER_BANDS)[number] }> {
|
||||
const since = new Date(ctx.now().getTime() - ACTIVE_DAYS * DAY);
|
||||
const count = await ctx.db.member.count({ where: { lastActiveAt: { gte: since } } });
|
||||
return { count, band: hub.activeMemberBand(count) };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* The App's modules (APP-1.0-PLAN §2, ROADMAP-v3 §7): House of Prayer, Prayer requests,
|
||||
* Announcements, Devotionals and Events, each switched on or off by the church (Settings →
|
||||
* Modules). Home and the tab bar only show what's on; the heartbeat reports the list
|
||||
* (`hub.appStatsSchema.modules`). All on by default. Kept in AppSetting `modules`.
|
||||
*/
|
||||
import { APP_MODULES, appModuleSchema, type AppModule } from '@crosscode/contracts';
|
||||
import type { Ctx } from './context.js';
|
||||
|
||||
const KEY = 'modules';
|
||||
|
||||
/** The modules switched on, in `APP_MODULES` order. */
|
||||
export async function enabledModules(ctx: Ctx): Promise<AppModule[]> {
|
||||
const saved = await ctx.settings.json<Record<string, unknown>>(KEY, {});
|
||||
return APP_MODULES.filter((m) => saved?.[m] !== false);
|
||||
}
|
||||
|
||||
/** Switches modules on or off (unknown names are refused); answers the new list. */
|
||||
export async function setModules(ctx: Ctx, change: Record<string, boolean>): Promise<AppModule[]> {
|
||||
const saved = { ...(await ctx.settings.json<Record<string, boolean>>(KEY, {})) };
|
||||
for (const [name, on] of Object.entries(change)) {
|
||||
const m = appModuleSchema.parse(name);
|
||||
if (on) delete saved[m];
|
||||
else saved[m] = false;
|
||||
}
|
||||
await ctx.settings.set(KEY, Object.keys(saved).length ? JSON.stringify(saved) : null);
|
||||
return enabledModules(ctx);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* What every page of the App needs, public (APP-1.0-PLAN §2): the church (from its profile in
|
||||
* Accounts), its colours made safe, its font pairing and corners, and the modules switched on.
|
||||
* The frontend builds the header, tab bar, manifest and icons from it.
|
||||
*/
|
||||
import { DEFAULT_CORNERS, type Church } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { buildPalette, type Palette } from '../church/palette.js';
|
||||
import { enabledModules } from '../modules.js';
|
||||
|
||||
/** The colour before the church has a profile (Cross Code's blue, as the Website's). */
|
||||
export const DEFAULT_COLOUR = '#1f4e79';
|
||||
/** The mockup's pairing (APP-1.0-PLAN, "Mockup"), until the church picks one in Accounts. */
|
||||
export const DEFAULT_FONT_PAIRING = 'warm';
|
||||
|
||||
export type AppInfo = {
|
||||
church: Church | null;
|
||||
/** The profile's short name, else the name cut to 12 characters (the home-screen label, §2). */
|
||||
shortName: string;
|
||||
palette: Omit<Palette, 'notes'>;
|
||||
style: { fontPairing: string; corners: string };
|
||||
modules: string[];
|
||||
/** The church's timezone (the profile's, else APP_TIMEZONE): days and slots are in it (§1). */
|
||||
timezone: string;
|
||||
};
|
||||
|
||||
export function shortNameFor(church: Pick<Church, 'name' | 'shortName'> | null): string {
|
||||
if (church?.shortName) return church.shortName;
|
||||
const name = church?.name?.trim() || 'Church App';
|
||||
return name.length <= 12 ? name : `${name.slice(0, 11).trimEnd()}…`;
|
||||
}
|
||||
|
||||
export async function appInfo(ctx: Ctx): Promise<AppInfo> {
|
||||
const [church, modules] = await Promise.all([churchProfile(ctx), enabledModules(ctx)]);
|
||||
const { notes: _notes, ...palette } = buildPalette(church?.branding.colours.primary ?? DEFAULT_COLOUR, church?.branding.colours.accent ?? null);
|
||||
return {
|
||||
church,
|
||||
shortName: shortNameFor(church),
|
||||
palette,
|
||||
style: {
|
||||
fontPairing: church?.branding.style?.fontPairing ?? DEFAULT_FONT_PAIRING,
|
||||
corners: church?.branding.style?.corners ?? DEFAULT_CORNERS,
|
||||
},
|
||||
modules,
|
||||
timezone: church?.timezone ?? ctx.config.timezone,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { createCtx, type Db } from '../src/context.js';
|
||||
import { stats } from '../src/hub/client.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
import { appVersion } from '../src/lib/version.js';
|
||||
import { shortNameFor } from '../src/public/app.js';
|
||||
import { harness, MEMBER } from './support/harness.js';
|
||||
|
||||
const DAY = 24 * 3600e3;
|
||||
|
||||
describe('the app', () => {
|
||||
it('answers /api/health with the product and version', async () => {
|
||||
const { app } = await harness();
|
||||
const res = await request(app).get('/api/health');
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body, { status: 'ok', product: 'app', version: appVersion(), db: true });
|
||||
});
|
||||
|
||||
it('says 503 when the database is down', async () => {
|
||||
const db = { $queryRaw: async () => { throw new Error('down'); } } as unknown as Db;
|
||||
const res = await request(createApp(createCtx(loadConfig({}), db))).get('/api/health');
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal(res.body.db, false);
|
||||
});
|
||||
|
||||
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
|
||||
const { app } = await harness();
|
||||
const res = await request(app).get('/api/nothing');
|
||||
assert.equal(res.status, 404);
|
||||
assert.equal(res.body.error.code, 'NOT_FOUND');
|
||||
assert.equal(res.headers['x-robots-tag'], 'noindex');
|
||||
assert.equal(res.headers['x-powered-by'], undefined);
|
||||
});
|
||||
|
||||
it('gives every page the church, its colours and the modules on (defaults before a profile)', async () => {
|
||||
const { app } = await harness();
|
||||
const res = await request(app).get('/api/v1/app');
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.church, null);
|
||||
assert.equal(res.body.shortName, 'Church App');
|
||||
assert.equal(res.body.palette.brand, '31 78 121');
|
||||
assert.equal(res.body.palette.notes, undefined);
|
||||
assert.deepEqual(res.body.style, { fontPairing: 'warm', corners: 'soft' });
|
||||
assert.deepEqual(res.body.modules, ['house-of-prayer', 'prayer-requests', 'announcements', 'devotionals', 'events']);
|
||||
assert.equal(res.body.timezone, 'Africa/Johannesburg');
|
||||
});
|
||||
|
||||
it('cuts a long name to 12 characters for the home screen, unless there is a short name', () => {
|
||||
assert.equal(shortNameFor({ name: 'Acacia Hill Community Church', shortName: null }), 'Acacia Hill…');
|
||||
assert.equal(shortNameFor({ name: 'Northpoint', shortName: null }), 'Northpoint');
|
||||
assert.equal(shortNameFor({ name: 'Acacia Hill Community Church', shortName: 'Acacia Hill' }), 'Acacia Hill');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the heartbeat', () => {
|
||||
it('reports the active-member band and the modules, never a name', async () => {
|
||||
const h = await harness();
|
||||
const now = h.ctx.now().getTime();
|
||||
for (let i = 0; i < 120; i++) {
|
||||
await h.db.member.create({ data: { id: `m-${i}`, name: `Person ${i}`, email: `p${i}@hope.test`, lastActiveAt: new Date(now - (i < 101 ? 89 : 91) * DAY) } });
|
||||
}
|
||||
await h.db.member.create({ data: { id: MEMBER, name: 'Never used it', email: 'never@hope.test' } });
|
||||
await h.ctx.settings.set('modules', JSON.stringify({ events: false }));
|
||||
const s = await stats(h.ctx);
|
||||
assert.ok(hub.appStatsSchema.safeParse(s).success);
|
||||
assert.equal(s.activeMembers90d, '101–300');
|
||||
assert.deepEqual(s.modules, ['house-of-prayer', 'prayer-requests', 'announcements', 'devotionals']);
|
||||
assert.doesNotMatch(JSON.stringify(s), /Person|hope\.test/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('config', () => {
|
||||
it('refuses production without a secret', () => {
|
||||
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /APP_SECRET/);
|
||||
});
|
||||
|
||||
it('defaults to the development ports and an 8-day sign-in up to 90 days', () => {
|
||||
const c = loadConfig({});
|
||||
assert.equal(c.port, 5400);
|
||||
assert.equal(c.publicUrl, 'http://localhost:3400');
|
||||
assert.equal(c.sessionDays, 8);
|
||||
assert.equal(c.sessionMaxDays, 90);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { cookieHeader, cookiesFrom, harness, MEMBER, PASTOR, SITE } from './support/harness.js';
|
||||
|
||||
const DAY = 24 * 3600e3;
|
||||
type H = Awaited<ReturnType<typeof harness>>;
|
||||
|
||||
/** Signs in from `returnTo` through the stand-in Accounts; returns the callback's response and the cookies after it. */
|
||||
async function signIn(h: H, returnTo = '/prayer?day=2026-12-02', cookies: Record<string, string> = {}, mfa = false) {
|
||||
const start = await request(h.app).get(`/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? '&mfa=1' : ''}`).set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(start.status, 303);
|
||||
const after = cookiesFrom(start, cookies);
|
||||
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
|
||||
return { start, back, cookies: cookiesFrom(back, after) };
|
||||
}
|
||||
|
||||
const me = (h: H, cookies: Record<string, string>) => request(h.app).get('/api/auth/me').set('Cookie', cookieHeader(cookies));
|
||||
|
||||
describe('signing in through Accounts', () => {
|
||||
it('sends people to Accounts with the page they were on, and brings them back to it', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'thandi@hope.test', name: 'Thandi Mokoena', amr: ['pwd'] };
|
||||
const { start, back, cookies } = await signIn(h);
|
||||
assert.match(start.headers.location!, /^https:\/\/accounts\.hope\.test\//);
|
||||
assert.deepEqual(h.fake.started, [{ returnTo: '/prayer?day=2026-12-02', requireTwoFactor: false }]);
|
||||
assert.equal(back.headers.location, `${SITE}/prayer?day=2026-12-02`);
|
||||
assert.match(String(back.headers['set-cookie']), /cca_session=.*HttpOnly/);
|
||||
const res = await me(h, cookies);
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body.member, { id: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test', roles: [] });
|
||||
});
|
||||
|
||||
it('makes anyone with an account a Member, keeping a copy of their profile', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'Thandi@Hope.test', phone_number: '+27820000000', phone_number_verified: false, whatsapp_opted_out: true, amr: ['pwd'] };
|
||||
await signIn(h);
|
||||
const m = await h.db.member.findUnique({ where: { id: MEMBER } });
|
||||
assert.equal(m!.email, 'thandi@hope.test');
|
||||
assert.equal(m!.phone, null, 'only a verified number is kept');
|
||||
assert.equal(m!.whatsappOptedOut, true);
|
||||
assert.deepEqual(m!.roles, []);
|
||||
});
|
||||
|
||||
it('refuses a foreign return address (back to Home instead)', async () => {
|
||||
const h = await harness();
|
||||
await request(h.app).get('/api/auth/signin?returnTo=https%3A%2F%2Fevil.test%2F');
|
||||
assert.equal(h.fake.started[0]!.returnTo, '/');
|
||||
});
|
||||
|
||||
it('says so when the App isn\'t linked to Accounts yet', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fme');
|
||||
assert.equal(res.status, 303);
|
||||
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fme`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the first Owner', () => {
|
||||
it('is whoever signs in with the Hub\'s admin email (verified)', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: PASTOR, email: 'Pastor@Hope.test' };
|
||||
const { cookies } = await signIn(h, '/admin');
|
||||
const res = await me(h, cookies);
|
||||
assert.deepEqual(res.body.member.roles, ['owner']);
|
||||
assert.deepEqual(res.body.activeRoles, ['owner']);
|
||||
assert.equal((await h.db.auditLog.findMany({ where: { action: 'first_owner_signed_in' } })).length, 1);
|
||||
});
|
||||
|
||||
it('never from an unverified email, and never a second one', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: PASTOR, email_verified: false };
|
||||
await signIn(h, '/');
|
||||
assert.deepEqual((await h.db.member.findUnique({ where: { id: PASTOR } }))!.roles, []);
|
||||
await h.db.member.create({ data: { id: MEMBER, name: 'Owner', email: 'owner@hope.test', roles: ['owner'] } });
|
||||
h.fake.next = { sub: PASTOR };
|
||||
await signIn(h, '/');
|
||||
assert.deepEqual((await h.db.member.findUnique({ where: { id: PASTOR } }))!.roles, []);
|
||||
});
|
||||
|
||||
it('becomes Owner even after signing in as a Member first', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: PASTOR, email_verified: false };
|
||||
await signIn(h, '/');
|
||||
h.fake.next = { sub: PASTOR };
|
||||
await signIn(h, '/');
|
||||
assert.deepEqual((await h.db.member.findUnique({ where: { id: PASTOR } }))!.roles, ['owner']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('2FA for every role (decision 7)', () => {
|
||||
it('asks Accounts once more for a second step when someone with a role heads for the admin', async () => {
|
||||
const h = await harness();
|
||||
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['prayer_coordinator'] } });
|
||||
h.fake.next = { sub: PASTOR, amr: ['pwd'] };
|
||||
const first = await signIn(h, '/admin');
|
||||
assert.equal(first.back.headers.location, `${SITE}/api/auth/signin?mfa=1&returnTo=%2Fadmin`);
|
||||
assert.equal(first.cookies.cca_session, undefined);
|
||||
// Accounts still came back without one: say why.
|
||||
const second = await signIn(h, '/admin', {}, true);
|
||||
assert.equal(second.back.headers.location, `${SITE}/auth/problem?code=TWO_FACTOR_NEEDED&returnTo=%2Fadmin`);
|
||||
});
|
||||
|
||||
it('lets someone with a role use the App as a Member without 2FA, but not the admin', async () => {
|
||||
const h = await harness();
|
||||
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['church_admin'] } });
|
||||
h.fake.next = { sub: PASTOR, amr: ['pwd'] };
|
||||
const { back, cookies } = await signIn(h, '/prayer');
|
||||
assert.equal(back.headers.location, `${SITE}/prayer`);
|
||||
const res = await me(h, cookies);
|
||||
assert.deepEqual(res.body.activeRoles, []);
|
||||
const admin = await request(h.app).get('/api/v1/admin/overview').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(admin.status, 403);
|
||||
assert.equal(admin.body.error.code, 'TWO_FACTOR_NEEDED');
|
||||
});
|
||||
|
||||
it('opens the admin with 2FA, and refuses a Member', async () => {
|
||||
const h = await harness();
|
||||
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['devotional_writer'] } });
|
||||
h.fake.next = { sub: PASTOR };
|
||||
const staff = await signIn(h, '/admin');
|
||||
const ok = await request(h.app).get('/api/v1/admin/overview').set('Cookie', cookieHeader(staff.cookies));
|
||||
assert.equal(ok.status, 200);
|
||||
assert.deepEqual(ok.body.activeMembers90d, { count: 1, band: '0–100' });
|
||||
assert.equal(ok.body.accounts.url, 'https://accounts.hope.test');
|
||||
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test' };
|
||||
const member = await signIn(h, '/');
|
||||
const no = await request(h.app).get('/api/v1/admin/overview').set('Cookie', cookieHeader(member.cookies));
|
||||
assert.equal(no.status, 403);
|
||||
assert.equal(no.body.error.code, 'FORBIDDEN');
|
||||
const out = await request(h.app).get('/api/v1/admin/overview');
|
||||
assert.equal(out.status, 401);
|
||||
});
|
||||
|
||||
it('lets only an Owner or Church admin switch modules', async () => {
|
||||
const h = await harness();
|
||||
await h.db.member.create({ data: { id: PASTOR, name: 'Pastor Sam', email: 'content@hope.test', roles: ['content_admin'] } });
|
||||
h.fake.next = { sub: PASTOR, email: 'content@hope.test' };
|
||||
let s = await signIn(h, '/admin');
|
||||
const put = (cookies: Record<string, string>, body: object) => request(h.app).put('/api/v1/admin/modules').set('Origin', SITE).set('Cookie', cookieHeader(cookies)).send(body);
|
||||
assert.equal((await put(s.cookies, { events: false })).status, 403);
|
||||
await h.db.member.update({ where: { id: PASTOR }, data: { roles: ['church_admin'] } });
|
||||
s = await signIn(h, '/admin');
|
||||
const res = await put(s.cookies, { events: false, devotionals: false });
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body.modules, ['house-of-prayer', 'prayer-requests', 'announcements']);
|
||||
assert.equal((await put(s.cookies, { chat: true })).status, 400);
|
||||
assert.equal((await put(s.cookies, { events: true })).body.modules.includes('events'), true);
|
||||
const app = await request(h.app).get('/api/v1/app');
|
||||
assert.deepEqual(app.body.modules, ['house-of-prayer', 'prayer-requests', 'announcements', 'events']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('staying signed in (decision 7)', () => {
|
||||
it('lasts 8 days, renewed by each visit, never past 90 days from the sign-in', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
|
||||
const { cookies } = await signIn(h, '/');
|
||||
// Every 7 days for 12 weeks: still signed in.
|
||||
for (let week = 1; week <= 12; week++) {
|
||||
h.clock.add(7 * DAY);
|
||||
assert.equal((await me(h, cookies)).status, 200, `week ${week}`);
|
||||
}
|
||||
// Day 84 + 7 = 91: past the 90-day limit, even though the last visit was a week ago.
|
||||
h.clock.add(7 * DAY);
|
||||
assert.equal((await me(h, cookies)).status, 401);
|
||||
});
|
||||
|
||||
it('ends after 8 days away', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
|
||||
const { cookies } = await signIn(h, '/');
|
||||
h.clock.add(7 * DAY);
|
||||
assert.equal((await me(h, cookies)).status, 200);
|
||||
h.clock.add(8 * DAY + 60e3);
|
||||
assert.equal((await me(h, cookies)).status, 401);
|
||||
});
|
||||
|
||||
it('renews the cookie too', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
|
||||
const { cookies } = await signIn(h, '/');
|
||||
h.clock.add(3 * DAY);
|
||||
const res = await me(h, cookies);
|
||||
const expires = /cca_session=[^;]+;.*Expires=([^;]+)/.exec(String(res.headers['set-cookie']))?.[1];
|
||||
assert.equal(new Date(expires!).toISOString().slice(0, 10), new Date(h.clock.now().getTime() + 8 * DAY).toISOString().slice(0, 10));
|
||||
});
|
||||
|
||||
it('ends at a back-channel logout from Accounts', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
|
||||
const { cookies } = await signIn(h, '/');
|
||||
const res = await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: JSON.stringify({ sub: MEMBER, sid: null }) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await me(h, cookies)).status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('active members (§10)', () => {
|
||||
it('counts a member once a day, in the church\'s timezone, only when signed in', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
|
||||
const { cookies } = await signIn(h, '/');
|
||||
await request(h.app).get('/api/v1/app');
|
||||
assert.equal((await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt, null, 'signing in alone isn\'t using the App');
|
||||
await me(h, cookies);
|
||||
const first = (await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt as Date;
|
||||
assert.equal(first.toISOString(), h.clock.now().toISOString());
|
||||
h.clock.add(3 * 3600e3);
|
||||
await me(h, cookies);
|
||||
assert.equal(((await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt as Date).toISOString(), first.toISOString(), 'one write a day');
|
||||
// 23:00 UTC is 01:00 the next day in Johannesburg: a new day.
|
||||
h.clock.set('2026-12-01T23:00:00Z');
|
||||
await me(h, cookies);
|
||||
assert.equal(((await h.db.member.findUnique({ where: { id: MEMBER } }))!.lastActiveAt as Date).toISOString(), '2026-12-01T23:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accounts\' calls', () => {
|
||||
const call = (h: H, body: object) => request(h.app).post('/api/accounts/v1/events').set('x-test-signed', 'yes').set('Content-Type', 'application/json').send(JSON.stringify(body));
|
||||
const base = { schema: 'crosscode.identity/1', callId: '44444444-4444-4444-8444-444444444444', occurredAt: '2026-12-01T06:00:00.000Z', sub: MEMBER };
|
||||
|
||||
it('refuses an unsigned call', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').send('{}');
|
||||
assert.equal(res.status, 401);
|
||||
});
|
||||
|
||||
it('keeps the profile copy up to date, WhatsApp STOP included', async () => {
|
||||
const h = await harness();
|
||||
await h.db.member.create({ data: { id: MEMBER, name: 'Thandi', email: 'thandi@hope.test' } });
|
||||
const res = await call(h, { ...base, type: 'user.updated', profile: { name: 'Thandi M', given_name: 'Thandi', family_name: 'M', email: 'T@Hope.test', email_verified: true, phone_number: '+27821112222', phone_number_verified: true, news_consent: { email: true, whatsapp: false }, whatsapp_opted_out: true } });
|
||||
assert.equal(res.status, 200);
|
||||
const m = await h.db.member.findUnique({ where: { id: MEMBER } });
|
||||
assert.equal(m!.name, 'Thandi M');
|
||||
assert.equal(m!.email, 't@hope.test');
|
||||
assert.equal(m!.phone, '+27821112222');
|
||||
assert.equal(m!.whatsappOptedOut, true);
|
||||
});
|
||||
|
||||
it('exports what the App keeps about someone, and forgets them when their account is deleted', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: MEMBER, email: 'm@hope.test', amr: ['pwd'] };
|
||||
const { cookies } = await signIn(h, '/');
|
||||
const exp = await call(h, { ...base, type: 'user.export', exportId: '55555555-5555-4555-8555-555555555555' });
|
||||
assert.equal(exp.body.product, 'app');
|
||||
assert.equal(exp.body.sections[0].records[0].email, 'm@hope.test');
|
||||
const del = await call(h, { ...base, type: 'user.deleted' });
|
||||
assert.equal(del.body.status, 'deleted');
|
||||
assert.equal(await h.db.member.findUnique({ where: { id: MEMBER } }), null);
|
||||
assert.equal((await me(h, cookies)).status, 401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* The App on an in-memory database, with a stand-in for `@crosscode/auth-client` (the real one is
|
||||
* tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts), linked to a
|
||||
* church's Accounts and registered with the Hub, and a clock the tests can move.
|
||||
*/
|
||||
import type { IdentityClaims } from '@crosscode/contracts';
|
||||
import type { AuthClientModule } from '../../src/auth/accounts.js';
|
||||
import { createApp } from '../../src/app.js';
|
||||
import { createCtx, type Ctx, type Db } from '../../src/context.js';
|
||||
import { loadConfig } from '../../src/lib/config.js';
|
||||
import { memoryDb, type MemoryDb } from './memoryDb.js';
|
||||
|
||||
export const SITE = 'https://app.hope.test';
|
||||
export const ACCOUNTS = 'https://accounts.hope.test';
|
||||
export const ADMIN_EMAIL = 'pastor@hope.test';
|
||||
export const INSTALL_ID = '6f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f';
|
||||
export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||
export const PASTOR = '11111111-1111-4111-8111-111111111111';
|
||||
export const MEMBER = '33333333-3333-4333-8333-333333333333';
|
||||
|
||||
/** What the stand-in Accounts answers with at the next callback. */
|
||||
export type FakeAccounts = {
|
||||
next: Partial<IdentityClaims> & { sub: string };
|
||||
started: { returnTo: string; requireTwoFactor: boolean }[];
|
||||
};
|
||||
|
||||
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
|
||||
return {
|
||||
schema: 'crosscode.identity/1',
|
||||
name: 'Pastor Sam',
|
||||
given_name: 'Sam',
|
||||
family_name: null,
|
||||
email: ADMIN_EMAIL,
|
||||
email_verified: true,
|
||||
phone_number: '+27821234567',
|
||||
phone_number_verified: true,
|
||||
news_consent: { email: false, whatsapp: false },
|
||||
amr: ['pwd', 'mfa'],
|
||||
two_factor: 'totp',
|
||||
privacy_notice_version: 1,
|
||||
...over,
|
||||
} as IdentityClaims;
|
||||
}
|
||||
|
||||
function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
|
||||
class SignInError extends Error {
|
||||
constructor(message: string, public code: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
return {
|
||||
SignInError,
|
||||
accountsClient: async () => ({
|
||||
startSignIn: async (returnTo: string, opts: { requireTwoFactor?: boolean } = {}) => {
|
||||
fake.started.push({ returnTo, requireTwoFactor: !!opts.requireTwoFactor });
|
||||
return { url: `${ACCOUNTS}/api/oidc/auth?mfa=${opts.requireTwoFactor ? 1 : 0}`, cookie: Buffer.from(JSON.stringify({ returnTo })).toString('base64url') };
|
||||
},
|
||||
finishSignIn: async (_url: URL, cookie: string | undefined) => {
|
||||
if (!cookie) throw new SignInError('expired', 'NO_PENDING');
|
||||
const { returnTo } = JSON.parse(Buffer.from(cookie, 'base64url').toString()) as { returnTo: string };
|
||||
return { claims: claims(fake.next), returnTo, idToken: `id-token-for-${fake.next.sub}` };
|
||||
},
|
||||
signOutUrl: (idToken?: string) => `${ACCOUNTS}/api/oidc/session/end?id_token_hint=${idToken ?? ''}`,
|
||||
verifyLogoutToken: async (token: string) => {
|
||||
try {
|
||||
return JSON.parse(token) as { sub: string; sid: string | null };
|
||||
} catch {
|
||||
throw new SignInError('bad', 'BAD_TOKEN');
|
||||
}
|
||||
},
|
||||
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
|
||||
if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE');
|
||||
return JSON.parse(raw.toString('utf8'));
|
||||
},
|
||||
}),
|
||||
} as unknown as AuthClientModule;
|
||||
}
|
||||
|
||||
/** A clock the tests move (`clock.add(ms)`); starts on 2026-12-01 08:00 SAST. */
|
||||
export function testClock(start = '2026-12-01T06:00:00Z') {
|
||||
let t = new Date(start).getTime();
|
||||
return { now: () => new Date(t), add: (ms: number) => { t += ms; }, set: (iso: string) => { t = new Date(iso).getTime(); } };
|
||||
}
|
||||
|
||||
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
|
||||
const db = memoryDb();
|
||||
const clock = testClock();
|
||||
const fake: FakeAccounts = { next: { sub: PASTOR }, started: [] };
|
||||
const config = loadConfig({ APP_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
|
||||
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake), now: clock.now });
|
||||
await ctx.settings.set('hub_install_id', INSTALL_ID);
|
||||
if (opts.linked !== false) {
|
||||
await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt('link-secret'), connectedAt: new Date() } });
|
||||
}
|
||||
return { db, ctx, fake, clock, app: createApp(ctx) };
|
||||
}
|
||||
|
||||
export type Harness = Awaited<ReturnType<typeof harness>> & { db: MemoryDb; ctx: Ctx };
|
||||
|
||||
/** `name=value` pairs from a response's Set-Cookie, for the next request. */
|
||||
export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Record<string, string> = {}): Record<string, string> {
|
||||
const out = { ...keep };
|
||||
for (const line of (res.headers['set-cookie'] as string[] | undefined) ?? []) {
|
||||
const [pair, ...attrs] = line.split(';');
|
||||
const i = pair!.indexOf('=');
|
||||
const name = pair!.slice(0, i).trim();
|
||||
const value = pair!.slice(i + 1).trim();
|
||||
const expired = attrs.some((a) => /^\s*expires=Thu, 01 Jan 1970/i.test(a)) || value === '';
|
||||
if (expired) delete out[name];
|
||||
else out[name] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* An in-memory stand-in for the Prisma client (from the Website's tests/support/memoryDb.ts): every
|
||||
* model the App uses, with the schema's defaults and unique fields, generic `where` matching
|
||||
* (equality, in / notIn, gt / gte / lt / lte, not, contains, has, AND / OR), `include` of the
|
||||
* relations below and `aggregate` sums. Enough to run the whole app in tests. Each module adds its
|
||||
* models' defaults here as it arrives.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const DEFAULTS: Record<string, () => Row> = {
|
||||
member: () => ({ phone: null, whatsappOptedOut: false, roles: [], lastActiveAt: null, lastSignInAt: null }),
|
||||
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
|
||||
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
|
||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
|
||||
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'] };
|
||||
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink']);
|
||||
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
||||
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
|
||||
};
|
||||
|
||||
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
||||
|
||||
function matchValue(actual: unknown, cond: unknown): boolean {
|
||||
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
||||
const c = cond as Record<string, unknown>;
|
||||
const insensitive = c.mode === 'insensitive';
|
||||
return Object.entries(c).every(([op, x]) => {
|
||||
switch (op) {
|
||||
case 'mode': return true;
|
||||
case 'equals': return v(actual) === v(x);
|
||||
case 'in': return (x as unknown[]).map(v).includes(v(actual));
|
||||
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
|
||||
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
|
||||
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
|
||||
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
|
||||
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
|
||||
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
||||
case 'has': return Array.isArray(actual) && actual.map(v).includes(v(x));
|
||||
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
|
||||
default: throw new Error(`memoryDb: no operator ${op}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
return v(actual) === v(cond);
|
||||
}
|
||||
|
||||
export function matches(row: Row, where: Row = {}): boolean {
|
||||
return Object.entries(where ?? {}).every(([k, cond]) => {
|
||||
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
|
||||
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
|
||||
if (k === 'NOT') return !matches(row, cond as Row);
|
||||
return matchValue(row[k], cond);
|
||||
});
|
||||
}
|
||||
|
||||
/** Prisma.DbNull / JsonNull (a nullable Json field set to null) are stored as null, as Postgres does. */
|
||||
const nulls = (x: unknown) => (x && typeof x === 'object' && /^(Db|Json)Null$/.test(x.constructor?.name ?? '') ? null : x);
|
||||
const clone = <T>(x: T): T => structuredClone(x && typeof x === 'object' && !Array.isArray(x) && !(x instanceof Date) ? Object.fromEntries(Object.entries(x).map(([k, y]) => [k, nulls(y)])) as T : x);
|
||||
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||
|
||||
function order(rows: Row[], orderBy?: Row | Row[]) {
|
||||
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
||||
return [...rows].sort((a, b) => {
|
||||
for (const o of list) {
|
||||
const [k, dir] = Object.entries(o)[0]!;
|
||||
const x = v(a[k]) as number;
|
||||
const y = v(b[k]) as number;
|
||||
const d = x < y ? -1 : x > y ? 1 : 0;
|
||||
if (d) return dir === 'desc' ? -d : d;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function prismaError(code: string, message: string) {
|
||||
return Object.assign(new Error(message), { code });
|
||||
}
|
||||
|
||||
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
const key = KEYS[name] ?? 'id';
|
||||
const table = () => {
|
||||
if (!tables.has(name)) tables.set(name, new Map());
|
||||
return tables.get(name)!;
|
||||
};
|
||||
const findWhere = (where: Row) => {
|
||||
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
||||
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
||||
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
||||
};
|
||||
const checkUnique = (row: Row, except?: unknown) => {
|
||||
for (const u of UNIQUE[name] ?? []) {
|
||||
if (row[u] == null) continue;
|
||||
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
|
||||
}
|
||||
};
|
||||
const api = {
|
||||
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
|
||||
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
||||
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
|
||||
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
|
||||
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
|
||||
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
|
||||
const rows = [...table().values()].filter((x) => matches(x, where));
|
||||
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
|
||||
},
|
||||
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
|
||||
create: async ({ data }: { data: Row }) => {
|
||||
const now = new Date();
|
||||
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
|
||||
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
|
||||
checkUnique(row);
|
||||
table().set(row[key], row);
|
||||
return clone(row);
|
||||
},
|
||||
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
|
||||
checkUnique(next, r[key]);
|
||||
table().set(r[key], next);
|
||||
return clone(next);
|
||||
},
|
||||
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
|
||||
return { count };
|
||||
},
|
||||
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
|
||||
const r = findWhere(where);
|
||||
return r ? api.update({ where, data: update }) : api.create({ data: create });
|
||||
},
|
||||
delete: async ({ where }: { where: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
|
||||
table().delete(r[key]);
|
||||
cascade(name, r[key]);
|
||||
return clone(r);
|
||||
},
|
||||
deleteMany: async ({ where }: { where?: Row } = {}) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
|
||||
return { count };
|
||||
},
|
||||
};
|
||||
const cascade = (from: string, id: unknown) => {
|
||||
if (from === 'member') for (const [k, r] of tables.get('session') ?? []) if (r.memberId === id) tables.get('session')!.delete(k);
|
||||
};
|
||||
const withIncludes = (row: Row, include?: Row) => {
|
||||
for (const [rel, on] of Object.entries(include ?? {})) {
|
||||
const spec = RELATIONS[name]?.[rel];
|
||||
if (!on || !spec) continue;
|
||||
const other = [...(tables.get(spec.model)?.values() ?? [])];
|
||||
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
|
||||
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
|
||||
}
|
||||
return row;
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
|
||||
|
||||
export function memoryDb(): MemoryDb {
|
||||
const tables = new Map<string, Map<unknown, Row>>();
|
||||
const models = new Map<string, ReturnType<typeof model>>();
|
||||
return new Proxy({} as MemoryDb, {
|
||||
get(_t, prop: string) {
|
||||
if (prop === 'tables') return tables;
|
||||
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
|
||||
if (prop === '$disconnect') return async () => {};
|
||||
if (prop === 'then') return undefined;
|
||||
if (!models.has(prop)) models.set(prop, model(prop, tables));
|
||||
return models.get(prop);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
// ES modules throughout, as Accounts and the Website (docs/APP-1.0-PLAN.md §1).
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"lib": ["ES2023"],
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"sourceMap": true,
|
||||
"rootDir": ".",
|
||||
"outDir": "dist",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "tests", "prisma.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// PM2 config template. Each install keeps its own copy as ecosystem.config.cjs (not in git, so
|
||||
// deploys never change it); crosscode creates it from this file the first time with the church's
|
||||
// PM2 names and ports.
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'app-backend',
|
||||
cwd: __dirname + '/backend',
|
||||
script: 'dist/index.js',
|
||||
env: { NODE_ENV: 'production' },
|
||||
max_memory_restart: '400M',
|
||||
},
|
||||
{
|
||||
name: 'app-frontend',
|
||||
cwd: __dirname + '/frontend',
|
||||
script: 'npm',
|
||||
args: 'start -- -p 3400',
|
||||
env: { NODE_ENV: 'production' },
|
||||
max_memory_restart: '400M',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema": "crosscode.env-template/1",
|
||||
"product": "app",
|
||||
"files": {
|
||||
"backend/.env": [
|
||||
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
|
||||
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
|
||||
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
|
||||
{ "name": "APP_SECRET", "layer": "generated", "required": true, "description": "Signs cookies and links, encrypts stored secrets: never change it" },
|
||||
{ "name": "APP_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address (app. or the Cross Code address)" },
|
||||
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
|
||||
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg", "description": "Until the church profile says its own" },
|
||||
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
|
||||
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
|
||||
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCP-…)" },
|
||||
{ "name": "HUB_ADMIN_NAME", "layer": "install" },
|
||||
{ "name": "HUB_ADMIN_EMAIL", "layer": "install", "description": "The first person to sign in with this address (through Accounts, verified) becomes the Owner" },
|
||||
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "APP_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
.next/
|
||||
next-env.d.ts
|
||||
.env*
|
||||
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
// Next.js 16's own flat configs, as the Website. Run with `npm run lint`.
|
||||
export default defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
{
|
||||
rules: {
|
||||
// The church's logo comes from its profile (another address): no Next image server.
|
||||
"@next/next/no-img-element": "off",
|
||||
},
|
||||
},
|
||||
globalIgnores([".next/**", "out/**", "next-env.d.ts", "public/sw.js"]),
|
||||
]);
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
// Everything under /api is the backend (docs/APP-1.0-PLAN.md §1). On a server nginx sends it
|
||||
// there; in development (and when Next is reached directly) this rewrite does.
|
||||
const api = (process.env.APP_API_URL || "http://127.0.0.1:5400").replace(/\/+$/, "");
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
poweredByHeader: false,
|
||||
transpilePackages: ["@crosscode/ui"],
|
||||
async rewrites() {
|
||||
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
|
||||
},
|
||||
async headers() {
|
||||
// Public content is indexed (ROADMAP-v3 §11); the member's own pages, the admin and every
|
||||
// prayer page never are (APP-1.0-PLAN §4, §11).
|
||||
const common = [
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
];
|
||||
const noindex = { key: "X-Robots-Tag", value: "noindex, nofollow" };
|
||||
const never = ["/admin", "/admin/:path*", "/me", "/me/:path*", "/prayer", "/prayer/:path*", "/auth/:path*", "/offline"];
|
||||
return [
|
||||
{ source: "/:path*", headers: common },
|
||||
...never.map((source) => ({ source, headers: [noindex] })),
|
||||
// The service worker is checked for updates on every visit (§2).
|
||||
{ source: "/sw.js", headers: [{ key: "Cache-Control", value: "no-cache" }, { key: "Service-Worker-Allowed", value: "/" }] },
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@crosscode/app-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Church App: the church-branded web app (PWA) for members, and its admin",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3400",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint src",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"lucide-react": "^0.536.0",
|
||||
"next": "^16.4.6",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "3.4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* The Church App's service worker (APP-1.0-PLAN §2, P2). No push and no notification permission
|
||||
* (decision 13): it only keeps the App usable offline.
|
||||
*
|
||||
* - Next's built files and the icons: from the cache, refreshed in the background.
|
||||
* - Pages: from the network; a copy is kept for offline. Offline, the last copy of that page shows
|
||||
* (the page says "You're offline"), else the offline page.
|
||||
* - A page rendered for a signed-in member (the proxy marks it `x-cca-signed-in: 1`) is kept apart,
|
||||
* and that cache is emptied as soon as a page comes back signed out or the member signs out, so
|
||||
* nothing personal stays on the phone for someone signed out.
|
||||
* - The API, the admin and signing in are never cached.
|
||||
*/
|
||||
const VERSION = "cca-v1";
|
||||
const SHELL = `${VERSION}-shell`;
|
||||
const PAGES = `${VERSION}-pages`;
|
||||
const PERSONAL = `${VERSION}-personal`;
|
||||
const OFFLINE = "/offline";
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(caches.open(SHELL).then((c) => c.addAll([OFFLINE, "/manifest.webmanifest"])).then(() => self.skipWaiting()));
|
||||
});
|
||||
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys()
|
||||
.then((keys) => Promise.all(keys.filter((k) => !k.startsWith(`${VERSION}-`)).map((k) => caches.delete(k))))
|
||||
.then(() => self.clients.claim()),
|
||||
);
|
||||
});
|
||||
|
||||
const neverCached = (path) => path.startsWith("/api/") || path.startsWith("/admin") || path.startsWith("/auth/");
|
||||
|
||||
async function fromCacheThenRefresh(request) {
|
||||
const cache = await caches.open(SHELL);
|
||||
const hit = await cache.match(request);
|
||||
const refresh = fetch(request).then((res) => {
|
||||
if (res.ok) cache.put(request, res.clone());
|
||||
return res;
|
||||
});
|
||||
return hit ?? refresh;
|
||||
}
|
||||
|
||||
async function page(request) {
|
||||
const url = new URL(request.url);
|
||||
try {
|
||||
const res = await fetch(request);
|
||||
const signedIn = res.headers.get("x-cca-signed-in") === "1";
|
||||
if (!signedIn) await caches.delete(PERSONAL);
|
||||
if (res.ok && !neverCached(url.pathname)) {
|
||||
const cache = await caches.open(signedIn ? PERSONAL : PAGES);
|
||||
await cache.put(url.pathname, res.clone());
|
||||
}
|
||||
return res;
|
||||
} catch {
|
||||
const personal = await caches.open(PERSONAL).then((c) => c.match(url.pathname));
|
||||
const saved = personal ?? (await caches.open(PAGES).then((c) => c.match(url.pathname)));
|
||||
return saved ?? (await caches.open(SHELL).then((c) => c.match(OFFLINE))) ?? Response.error();
|
||||
}
|
||||
}
|
||||
|
||||
self.addEventListener("fetch", (event) => {
|
||||
const { request } = event;
|
||||
if (request.method !== "GET") {
|
||||
// Signing out: forget the member's pages at once.
|
||||
if (new URL(request.url).pathname === "/api/auth/signout") event.waitUntil(caches.delete(PERSONAL));
|
||||
return;
|
||||
}
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== self.location.origin) return;
|
||||
if (url.pathname.startsWith("/_next/static/") || url.pathname.startsWith("/app-icon/")) {
|
||||
event.respondWith(fromCacheThenRefresh(request));
|
||||
return;
|
||||
}
|
||||
if (request.mode === "navigate" && !neverCached(url.pathname)) event.respondWith(page(request));
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { api, loadMe, ROLE_NAMES, SESSION_COOKIE, signInHref } from "@/lib/load";
|
||||
|
||||
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
|
||||
|
||||
type Overview = {
|
||||
activeMembers90d: { count: number; band: string };
|
||||
modules: string[];
|
||||
hub: { connected: boolean; state: string; lastHeartbeatAt: string | null };
|
||||
accounts: { url: string; connectedAt: string } | null;
|
||||
};
|
||||
|
||||
const MODULE_NAMES: Record<string, string> = {
|
||||
"house-of-prayer": "House of Prayer",
|
||||
"prayer-requests": "Prayer requests",
|
||||
announcements: "Announcements",
|
||||
devotionals: "Devotionals",
|
||||
events: "Events",
|
||||
};
|
||||
|
||||
async function loadOverview(): Promise<Overview | null> {
|
||||
const session = (await cookies()).get(SESSION_COOKIE)?.value;
|
||||
if (!session) return null;
|
||||
try {
|
||||
const res = await fetch(`${api}/api/v1/admin/overview`, { headers: { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(session)}` }, cache: "no-store" });
|
||||
if (res.ok) return (await res.json()) as Overview;
|
||||
} catch {
|
||||
// The backend is starting or down.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function Page({ children }: { children: React.ReactNode }) {
|
||||
return <main className="mx-auto max-w-4xl space-y-6 px-4 py-10">{children}</main>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin's dashboard (APP-1.0-PLAN §10; the Website's and Events' layout, decision 9). For now
|
||||
* the foundation: who's using the App, the modules on, and the links to the Hub and Accounts. The
|
||||
* side menu, setup checklist and each module's pages come with the modules.
|
||||
*/
|
||||
export default async function Admin() {
|
||||
const me = await loadMe();
|
||||
if (!me) {
|
||||
return (
|
||||
<Page>
|
||||
<h1 className="text-2xl font-semibold">The App's admin</h1>
|
||||
<a href={signInHref("/admin", true)} className="cca-btn">Sign in</a>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!me.member.roles.length) {
|
||||
return (
|
||||
<Page>
|
||||
<h1 className="text-2xl font-semibold">No access to the admin</h1>
|
||||
<p className="text-gray-600">Your account doesn't have a role in the App. Ask the App's Owner or a Church admin if you need one.</p>
|
||||
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (!me.mfa) {
|
||||
return (
|
||||
<Page>
|
||||
<h1 className="text-2xl font-semibold">Two-step sign-in needed</h1>
|
||||
<p className="text-gray-600">Every role in the App needs a sign-in with your second step. Turn on two-step sign-in in your church account if it isn't yet, then sign in again.</p>
|
||||
<a href={signInHref("/admin", true)} className="cca-btn">Sign in with two-step</a>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
const o = await loadOverview();
|
||||
return (
|
||||
<Page>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Dashboard</h1>
|
||||
<p className="text-sm text-gray-600">{me.member.name} · {me.member.roles.map((r) => ROLE_NAMES[r]).join(", ")}</p>
|
||||
</div>
|
||||
{!o ? (
|
||||
<p className="text-gray-600">The dashboard can't be loaded right now. Please try again in a minute.</p>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<section className="cca-card">
|
||||
<h2 className="text-sm text-gray-600">Active members (90 days)</h2>
|
||||
<p className="mt-1 text-3xl font-semibold">{o.activeMembers90d.count}</p>
|
||||
<p className="text-sm text-gray-600">Band {o.activeMembers90d.band}</p>
|
||||
</section>
|
||||
<section className="cca-card">
|
||||
<h2 className="text-sm text-gray-600">Modules on</h2>
|
||||
<ul className="mt-1 text-sm">{o.modules.map((m) => <li key={m}>{MODULE_NAMES[m] ?? m}</li>)}</ul>
|
||||
</section>
|
||||
<section className="cca-card">
|
||||
<h2 className="text-sm text-gray-600">Connections</h2>
|
||||
<p className="mt-1 text-sm">Cross Code Hub: {o.hub.connected ? `connected (${o.hub.state})` : "not connected"}</p>
|
||||
<p className="text-sm">Accounts: {o.accounts ? "linked" : "not linked yet"}</p>
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { ImageResponse } from "next/og";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { churchIconUrl, ICON_SIZES, initials, rgb, type IconKind } from "@/lib/icon";
|
||||
|
||||
/**
|
||||
* The App's icon as a PNG (APP-1.0-PLAN §2): the church's icon from its profile, on its primary
|
||||
* colour, else its initials on its primary colour. `maskable` keeps everything inside the middle
|
||||
* 80% (Android crops the rest); `apple` is the iPhone's home-screen icon. The manifest and layout
|
||||
* link here with a version, so a new icon shows at once.
|
||||
*/
|
||||
export async function GET(_request: Request, { params }: { params: Promise<{ kind: string }> }) {
|
||||
const { kind } = await params;
|
||||
if (!(kind in ICON_SIZES)) return new Response("Not found", { status: 404 });
|
||||
const size = ICON_SIZES[kind as IconKind];
|
||||
const app = await loadApp();
|
||||
const icon = churchIconUrl(app);
|
||||
const maskable = kind === "maskable";
|
||||
const inner = Math.round(size * (maskable ? 0.62 : icon ? 0.86 : 1));
|
||||
const label = initials(app.church?.shortName || app.church?.name || "");
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", background: rgb(app.palette.brand), color: rgb(app.palette.onBrand), borderRadius: kind === "favicon" ? size * 0.22 : 0 }}>
|
||||
{icon ? (
|
||||
<img src={icon} alt="" width={inner} height={inner} style={{ borderRadius: maskable ? 0 : size * 0.12 }} />
|
||||
) : (
|
||||
<div style={{ display: "flex", fontSize: Math.round(inner * (label.length > 1 ? 0.42 : 0.56)), fontWeight: 700, letterSpacing: label.length > 1 ? -size * 0.01 : 0 }}>{label}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
{ width: size, height: size, headers: { "Cache-Control": "public, max-age=86400" } },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { signInHref } from "@/lib/load";
|
||||
|
||||
export const metadata: Metadata = { title: "Signing in", robots: { index: false, follow: false } };
|
||||
|
||||
/** What went wrong with a sign-in (the backend's auth/routes.ts sends people here with a code). */
|
||||
const PROBLEMS: Record<string, { title: string; text: string }> = {
|
||||
TWO_FACTOR_NEEDED: {
|
||||
title: "Two-step sign-in needed",
|
||||
text: "Your role in the App needs a sign-in with a second step. Turn on two-step sign-in in your church account, then try again.",
|
||||
},
|
||||
ACCOUNTS_NOT_LINKED: {
|
||||
title: "The App isn't linked to your church's sign-in yet",
|
||||
text: "It links by itself shortly after it's installed. Please try again in a minute. If this keeps happening, contact your church.",
|
||||
},
|
||||
ACCOUNTS_UNAVAILABLE: {
|
||||
title: "Signing in isn't available right now",
|
||||
text: "The App can't reach your church's sign-in at the moment. Please try again in a few minutes.",
|
||||
},
|
||||
EXPIRED: { title: "The sign-in took too long", text: "Please try again." },
|
||||
SIGNIN_FAILED: { title: "That didn't work", text: "Something went wrong while signing you in. Please try again." },
|
||||
};
|
||||
|
||||
export default async function Problem({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
|
||||
const q = await searchParams;
|
||||
const code = typeof q.code === "string" ? q.code : "";
|
||||
const returnTo = typeof q.returnTo === "string" && q.returnTo.startsWith("/") && !q.returnTo.startsWith("//") ? q.returnTo : "/";
|
||||
const p = PROBLEMS[code] ?? PROBLEMS.SIGNIN_FAILED!;
|
||||
return (
|
||||
<main className="mx-auto max-w-xl space-y-4 px-4 py-16">
|
||||
<h1 className="cca-h1">{p.title}</h1>
|
||||
<p className="text-gray-600">{p.text}</p>
|
||||
<div className="flex gap-3">
|
||||
<a href={signInHref(returnTo, code === "TWO_FACTOR_NEEDED")} className="cca-btn">Try again</a>
|
||||
<Link href="/" className="cca-btn-quiet">Go to the App</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import { requireModule } from "@/lib/module";
|
||||
|
||||
export const metadata: Metadata = { title: "Devotional" };
|
||||
|
||||
/** Today's devotional and the archive (APP-1.0-PLAN §6). */
|
||||
export default async function Devotional() {
|
||||
await requireModule("devotionals");
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Devotional</h1>
|
||||
<ComingSoon title="Today">Today's Bible passage and devotional will show here, with Read in YouVersion.</ComingSoon>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import { requireModule } from "@/lib/module";
|
||||
|
||||
export const metadata: Metadata = { title: "Events" };
|
||||
|
||||
/** Events (APP-1.0-PLAN §7): the App's simple events and those from Cross Events and the Website. */
|
||||
export default async function Events() {
|
||||
await requireModule("events");
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Events</h1>
|
||||
<ComingSoon title="What's on">The church's events will show here.</ComingSoon>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/*
|
||||
* The Church App (APP-1.0-PLAN §1, §2): mobile first, a centred column on a desktop, the bottom tab
|
||||
* bar. The layout sets the church's colours as CSS variables (--brand, --on-brand, --brand-text,
|
||||
* --brand-tint, --accent, …) and its fonts and corners as attributes (data-cc-fonts /
|
||||
* data-cc-corners, @crosscode/ui).
|
||||
*/
|
||||
|
||||
:root {
|
||||
--brand: 31 78 121;
|
||||
--brand-dark: 25 62 97;
|
||||
--on-brand: 255 255 255;
|
||||
--brand-text: 31 78 121;
|
||||
--brand-tint: 241 244 248;
|
||||
--accent: 87 113 148;
|
||||
--on-accent: 255 255 255;
|
||||
/* The tab bar's height, above the iPhone's home indicator. */
|
||||
--cca-tabs: calc(4rem + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-gray-50 text-gray-900 antialiased;
|
||||
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif);
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
|
||||
@layer components {
|
||||
/* The member screens: phone width first, a centred column on anything wider. */
|
||||
.cca-column { @apply mx-auto w-full max-w-xl px-4; }
|
||||
.cca-card { @apply rounded-cc border border-gray-200 bg-white p-4 shadow-sm; }
|
||||
.cca-btn {
|
||||
@apply inline-flex min-h-11 items-center justify-center gap-2 rounded-cc bg-brand px-4 py-2 text-sm font-semibold text-brand-on hover:bg-brand-dark;
|
||||
@apply focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand;
|
||||
}
|
||||
.cca-btn-quiet {
|
||||
@apply inline-flex min-h-11 items-center justify-center gap-2 rounded-cc border border-gray-300 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50;
|
||||
@apply focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand;
|
||||
}
|
||||
.cca-h1 { @apply font-heading text-2xl font-semibold text-gray-900; }
|
||||
.cca-h2 { @apply font-heading text-lg font-semibold text-gray-900; }
|
||||
.cca-muted { @apply text-sm text-gray-600; }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { iconHref, rgb } from "@/lib/icon";
|
||||
import { RegisterServiceWorker } from "@/components/RegisterServiceWorker";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const app = await loadApp();
|
||||
const name = app.church?.name ?? "Church App";
|
||||
return {
|
||||
title: { default: name, template: `%s · ${name}` },
|
||||
applicationName: app.shortName,
|
||||
manifest: "/manifest.webmanifest",
|
||||
icons: { icon: iconHref("favicon", app), apple: iconHref("apple", app) },
|
||||
// iPhone: opened from the home screen it runs full screen, with this name under the icon (§2).
|
||||
appleWebApp: { capable: true, title: app.shortName, statusBarStyle: "default" },
|
||||
formatDetection: { telephone: false },
|
||||
};
|
||||
}
|
||||
|
||||
export async function generateViewport(): Promise<Viewport> {
|
||||
const app = await loadApp();
|
||||
return { themeColor: rgb(app.palette.brand), width: "device-width", initialScale: 1, viewportFit: "cover" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every page: the church's fonts and corners (shared brand style, @crosscode/ui) and its colours,
|
||||
* made safe by the backend, as variables (APP-1.0-PLAN §2).
|
||||
*/
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const app = await loadApp();
|
||||
const p = app.palette;
|
||||
const vars = `:root{--brand:${p.brand};--brand-dark:${p.brandDark};--on-brand:${p.onBrand};--brand-text:${p.brandText};--brand-tint:${p.brandTint};--accent:${p.accent};--on-accent:${p.onAccent}}`;
|
||||
return (
|
||||
<html lang={app.church?.locale ?? "en-ZA"} {...brandAttributes(app.style)}>
|
||||
<head>
|
||||
<style>{vars.replace(/[<>]/g, "")}</style>
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
<RegisterServiceWorker />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { loadApp } from "@/lib/load";
|
||||
import { iconHref, rgb } from "@/lib/icon";
|
||||
|
||||
/**
|
||||
* The web app manifest (APP-1.0-PLAN §2, P1), built from the church profile: its name, short name
|
||||
* (the profile's, else the name cut to 12 characters), icons (192, 512 and a maskable one on the
|
||||
* primary colour), the primary colour as the theme, standalone, and a start address that says the
|
||||
* App was opened from the home screen. Made per request: the church's name, colours and icon can
|
||||
* change at any time, and are never baked in at build.
|
||||
*/
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
const app = await loadApp();
|
||||
const name = app.church?.name ?? "Church App";
|
||||
const manifest = {
|
||||
name,
|
||||
short_name: app.shortName,
|
||||
description: `${name}: prayer, news, devotionals and events.`,
|
||||
id: "/",
|
||||
start_url: "/?source=homescreen",
|
||||
scope: "/",
|
||||
display: "standalone",
|
||||
orientation: "portrait",
|
||||
background_color: "#ffffff",
|
||||
theme_color: rgb(app.palette.brand),
|
||||
lang: app.church?.locale ?? "en-ZA",
|
||||
icons: [
|
||||
{ src: iconHref("192", app), sizes: "192x192", type: "image/png", purpose: "any" },
|
||||
{ src: iconHref("512", app), sizes: "512x512", type: "image/png", purpose: "any" },
|
||||
{ src: iconHref("maskable", app), sizes: "512x512", type: "image/png", purpose: "maskable" },
|
||||
],
|
||||
};
|
||||
return new Response(JSON.stringify(manifest), {
|
||||
headers: { "Content-Type": "application/manifest+json", "Cache-Control": "public, max-age=300" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { loadMe, ROLE_NAMES, signInHref } from "@/lib/load";
|
||||
|
||||
export const metadata: Metadata = { title: "Me", robots: { index: false, follow: false } };
|
||||
|
||||
/**
|
||||
* Me (APP-1.0-PLAN §1): signed out, why and how to sign in; signed in, who they are, the admin for
|
||||
* someone with a role, and signing out. Their prayer, requests and notification settings come with
|
||||
* their modules (§3, §4, §8).
|
||||
*/
|
||||
export default async function Me() {
|
||||
const me = await loadMe();
|
||||
if (!me) {
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Me</h1>
|
||||
<section className="cca-card space-y-3">
|
||||
<p>Sign in with your church account to book a prayer slot, ask for prayer and choose what the App sends you.</p>
|
||||
<a href={signInHref("/me")} className="cca-btn">Sign in</a>
|
||||
</section>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
const roles = me.member.roles;
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">{me.member.name}</h1>
|
||||
<section className="cca-card space-y-1">
|
||||
<p className="cca-muted">{me.member.email}</p>
|
||||
<p className="text-sm">{roles.length ? roles.map((r) => ROLE_NAMES[r]).join(", ") : "Member"}</p>
|
||||
</section>
|
||||
{roles.length > 0 && (
|
||||
<section className="cca-card space-y-2">
|
||||
<h2 className="cca-h2">The App's admin</h2>
|
||||
{me.mfa ? (
|
||||
<Link href="/admin" className="cca-btn">Open the admin</Link>
|
||||
) : (
|
||||
<>
|
||||
<p className="cca-muted">Your role needs a sign-in with your second step (two-factor).</p>
|
||||
<a href={signInHref("/admin", true)} className="cca-btn">Sign in to the admin</a>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<form action="/api/auth/signout" method="post">
|
||||
<button type="submit" className="cca-btn-quiet w-full">Sign out</button>
|
||||
</form>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import Link from "next/link";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">Page not found</h1>
|
||||
<p className="cca-muted">That page isn't here. It may have moved, or the church has switched it off.</p>
|
||||
<Link href="/" className="cca-btn">Go to Home</Link>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
|
||||
export const metadata: Metadata = { title: "Offline", robots: { index: false, follow: false } };
|
||||
|
||||
/** What the service worker shows for a page it never saved, while there's no connection (§2). */
|
||||
export default function Offline() {
|
||||
return (
|
||||
<main className="mx-auto max-w-xl space-y-4 px-4 py-16 text-center">
|
||||
<h1 className="cca-h1">You're offline</h1>
|
||||
<p className="text-gray-600">This page wasn't saved on your phone. Connect to the internet and try again.</p>
|
||||
<Link href="/" className="cca-btn">Go to Home</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import { InstallCard } from "@/components/InstallCard";
|
||||
import { firstName, greeting, loadApp, loadMe } from "@/lib/load";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const app = await loadApp();
|
||||
const name = app.church?.name ?? "Church App";
|
||||
return { title: { absolute: name }, description: `${name}: prayer, news, devotionals and events, on your phone.` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Home (APP-1.0-PLAN §1, mockup "Home"): the greeting, then what's on, in this order: the
|
||||
* campaign, the member's next slot and today's prayer clock (House of Prayer), today's devotional,
|
||||
* a pinned announcement. Each module fills its card as it arrives.
|
||||
*/
|
||||
export default async function Home() {
|
||||
const [app, me] = await Promise.all([loadApp(), loadMe()]);
|
||||
const on = new Set(app.modules);
|
||||
const name = app.church?.name ?? "your church";
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">
|
||||
{me ? `${greeting(app.timezone)}, ${firstName(me.member.name)}` : `Welcome to ${name}`}
|
||||
</h1>
|
||||
<InstallCard name={app.shortName} />
|
||||
{on.has("house-of-prayer") && <ComingSoon title="House of Prayer">Today's prayer clock and your next slot will show here.</ComingSoon>}
|
||||
{on.has("devotionals") && <ComingSoon title="Today's devotional">Today's Bible passage and devotional will show here.</ComingSoon>}
|
||||
{on.has("announcements") && <ComingSoon title="Announcements">News from {name} will show here.</ComingSoon>}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ComingSoon } from "@/components/ComingSoon";
|
||||
import { requireModule } from "@/lib/module";
|
||||
|
||||
// Every prayer page is noindex (APP-1.0-PLAN §4, §11; next.config.ts sends the header too).
|
||||
export const metadata: Metadata = { title: "House of Prayer", robots: { index: false, follow: false } };
|
||||
|
||||
/** The House of Prayer (APP-1.0-PLAN §3): the 24-hour clock, booking, campaigns. */
|
||||
export default async function Prayer() {
|
||||
await requireModule("house-of-prayer");
|
||||
return (
|
||||
<AppShell>
|
||||
<h1 className="cca-h1">House of Prayer</h1>
|
||||
<ComingSoon title="The prayer wall">The 24-hour prayer clock, with the hours still open, will show here.</ComingSoon>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user