Compare commits
205
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
19c12ef09e | ||
|
|
a9215ac4e4 | ||
|
|
25100bd749 | ||
|
|
f68f695934 | ||
|
|
ebcee43594 | ||
|
|
7f681c9e81 | ||
|
|
a75d2f7b46 | ||
|
|
2edb9f681a | ||
|
|
d299442015 | ||
|
|
9994cbd760 | ||
|
|
0d6afc7cd1 | ||
|
|
3539bf0ac0 | ||
|
|
ff3d9aefa2 | ||
|
|
8c4f5f244c | ||
|
|
edac4ee767 | ||
|
|
090453e14a | ||
|
|
9c87208428 | ||
|
|
f931226e74 | ||
|
|
1940ff2a91 | ||
|
|
2d4d9ea871 | ||
|
|
28085d92ba | ||
|
|
fbe814b2d9 | ||
|
|
fe4310352e | ||
|
|
db12d17796 | ||
|
|
22d7e54008 | ||
|
|
8c213d6d84 | ||
|
|
48abc06db7 | ||
|
|
da283f3cbb | ||
|
|
2a4cf7acab | ||
|
|
a3ac3da5a5 | ||
|
|
8e52bd2d33 | ||
|
|
7b49ec2b70 | ||
|
|
d3e04127f3 | ||
|
|
2fb7ac57da | ||
|
|
81c01d8a9f | ||
|
|
2335fd46e4 | ||
|
|
f58711603a | ||
|
|
d1354a6a17 | ||
|
|
175a6b41eb | ||
|
|
80d8e903dd | ||
|
|
35501deb0d | ||
|
|
79e1450df6 | ||
|
|
6905a19c8c | ||
|
|
dcc22a5c16 | ||
|
|
e6c91c3705 | ||
|
|
925b5fbd8b | ||
|
|
58cadbf472 | ||
|
|
f6a536ad64 | ||
|
|
05d808b74c | ||
|
|
20a23a3ba8 | ||
|
|
9c9c96dd2c | ||
|
|
f73761f956 | ||
|
|
62441ad437 | ||
|
|
7814a64cf7 | ||
|
|
679f61febf | ||
|
|
723bb15a5e | ||
|
|
dd0e5e17b3 | ||
|
|
7216035e49 | ||
|
|
9bf1739734 | ||
|
|
0b99686ca7 | ||
|
|
6ffad24db1 | ||
|
|
268c9cde88 | ||
|
|
9086b549a8 | ||
|
|
154bb94da7 | ||
|
|
312c32c6cb | ||
|
|
283e75737d | ||
|
|
53e5de3f14 | ||
|
|
085265392e | ||
|
|
d8ed238042 | ||
|
|
b767b45e64 | ||
|
|
193a338ed2 | ||
|
|
2ba755145d | ||
|
|
6be1a2782d | ||
|
|
37a1f6acf1 | ||
|
|
9b8f10e3c8 | ||
|
|
84c5b0c08e | ||
|
|
3caa1d1e1a | ||
|
|
5ed7201efa | ||
|
|
138c73e20c | ||
|
|
58960b5e93 | ||
|
|
79121bc447 | ||
|
|
36ceb358b8 | ||
|
|
a3a158faa8 | ||
|
|
ae604268e0 | ||
|
|
ae122a664a | ||
|
|
62d9728b95 | ||
|
|
ee129fbd87 | ||
|
|
10be55d261 | ||
|
|
ed97956a2f | ||
|
|
e79e5a11f9 | ||
|
|
66557c7f1d | ||
|
|
f4b6a41f83 | ||
|
|
2eaedb8cec | ||
|
|
45a2edd4cc | ||
|
|
0e3534f29f | ||
|
|
9954e66c33 | ||
|
|
9523976044 | ||
|
|
06eedd0499 | ||
|
|
75aeae1ff2 | ||
|
|
d0df78abe3 | ||
|
|
029d3f4e89 | ||
|
|
0b500934cb | ||
|
|
86ddc2e6d9 | ||
|
|
5fbfd28014 | ||
|
|
703fa7804f | ||
|
|
9eb4d345c6 | ||
|
|
e4730120ab | ||
|
|
ac6800d9de | ||
|
|
fc1e97eba8 | ||
|
|
cd84838e78 | ||
|
|
6c03a10a24 | ||
|
|
fe54d9ab7b | ||
|
|
0d48f81c02 | ||
|
|
c1383d62aa | ||
|
|
9dc42e7481 | ||
|
|
a01465a4bb | ||
|
|
e59e7488a3 | ||
|
|
1fe94bf70e | ||
|
|
970a60d55f | ||
|
|
da0a7b5f15 | ||
|
|
e5bb98c81f | ||
|
|
9dd599cd80 | ||
|
|
8dc2c8ad68 | ||
|
|
1bb64b1902 | ||
|
|
3d28ec6edb | ||
|
|
d7f30d348a | ||
|
|
87069c85dd | ||
|
|
1f9f2f4640 | ||
|
|
544cd30656 | ||
|
|
55a924afb6 | ||
|
|
e9f1e46781 | ||
|
|
3e85921a35 | ||
|
|
8899c97a9c | ||
|
|
e04bfac208 | ||
|
|
7677f54056 | ||
|
|
ce1c978f21 | ||
|
|
8542d19be0 | ||
|
|
4cc30c1445 | ||
|
|
d91d956e78 | ||
|
|
9f07ecf0dd | ||
|
|
74df4aa7b5 | ||
|
|
72a6283024 | ||
|
|
86711699cf | ||
|
|
d28029e96e | ||
|
|
e65e26202a | ||
|
|
ca55142f6f | ||
|
|
1b94814f67 | ||
|
|
0b70a87669 | ||
|
|
ead07ef932 | ||
|
|
d8312f4b33 | ||
|
|
a9239d429a | ||
|
|
405b5f1b92 | ||
|
|
c8c5db46bc | ||
|
|
031fb11e02 | ||
|
|
16d3ffe6ba | ||
|
|
eac6564e11 | ||
|
|
8f78fcc75c | ||
|
|
cacbb16895 | ||
|
|
08b58ae310 | ||
|
|
e32a3b6144 | ||
|
|
bbcafe61b9 | ||
|
|
a85347bff8 | ||
|
|
8856d6b35d | ||
|
|
8ee64bb9c9 | ||
|
|
293a9b73e5 | ||
|
|
621821f5c0 | ||
|
|
88b3e1fb36 | ||
|
|
70c471666b | ||
|
|
cc18b7b514 | ||
|
|
4b28fc485b | ||
|
|
793831ca44 | ||
|
|
4b033a1d1d |
+455
@@ -2,6 +2,461 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## agent@1.7.0 + contracts@1.23.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in the server agent (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
|
||||
- **Contracts 1.23.0:** the `seed-scenario` job (`church`, `scenario`, optional `adminEmail`; 45
|
||||
minutes): a whole demo scenario in one job, on whatever the church has installed.
|
||||
`SEED_SCENARIO_JOB_MIN_AGENT` (1.7.0). Additive.
|
||||
- **Agent 1.7.0:** `seed-scenario` → `crosscode demo <church> --scenario <s>`; `seed-demo` for `accounts` and `app` (`crosscode demo <church> <product> …`),
|
||||
and `scenario` passed on as `--scenario` for every product (contracts `SEED_SCENARIO_MIN_AGENT`,
|
||||
`SEED_APP_DEMO_MIN_AGENT`). Events' jobs keep their old form (no product).
|
||||
- **crosscode script:** `crosscode demo <church> --scenario <s>` (no product, no profile) loads the
|
||||
scenario on every product the church has here, in deploy order, skipping the others; checks
|
||||
every installed release against the scenario minimums first; each product takes its own
|
||||
backup; the first failure stops the rest and names what's out of step (`loaded`, `skipped` in
|
||||
the report). Events' demo is now `cmd_demo_events`. `crosscode demo <church> app …` says the
|
||||
App's demo comes with App 1.0.0, instead of misreading `app` as a second church.
|
||||
|
||||
## website@1.8.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in the Church Website (docs/APP-1.0-PLAN.md §12, "Demo scenarios"). No
|
||||
migration. Details in `apps/website/CHANGELOG.md`.
|
||||
|
||||
- **Website 1.8.0:** `npm run demo -- --profile <p> --scenario <p>` loads a profile as part of its
|
||||
demo scenario: the leaders are the scenario's people (`@crosscode/demo`), the pastor the home
|
||||
page's and the messages' speaker; with a linked Cross Events, Events' events show through the
|
||||
feed (Show events from, fetched at once) instead of the profile's own.
|
||||
- **crosscode script:** `crosscode demo <church> website … --scenario <p>` passes it on and refuses a
|
||||
Website before 1.8.0; the Website installs and builds `packages/demo`.
|
||||
|
||||
## contracts@1.22.0 - 2026-11-30
|
||||
|
||||
Bible translations for the Church App's devotionals (docs/BIBLE-PERMISSIONS.md, APP-1.0-PLAN.md §6
|
||||
and decision 14). Additive except for the notice texts and one translation's name; no id changes,
|
||||
nothing has shown them yet.
|
||||
|
||||
- **Only free translations in 1.0:** each translation has a `licence` ("public-domain" or
|
||||
"permission"); `FREE_BIBLE_TRANSLATION_IDS` (KJV, BSB) is what the Hub and the App offer, and
|
||||
`checkDevotionalCsv(text, { translations })` refuses any other, naming the publisher to ask.
|
||||
- **The Berean Standard Bible (`BSB`)**, public domain since 2023, YouVersion 3034. The CSV template
|
||||
and the devotionals sample now quote the BSB and the KJV.
|
||||
- **Notices corrected** to each publisher's current wording: NLT (Tyndale House Ministries), ESV
|
||||
(ESV Text Edition: 2025, the Creative Commons and translation clauses), AFR53 and AFR83 (the
|
||||
Bible Society's digital short form). The NIV and NKJV notices were already right.
|
||||
- **`AFR83` is named "Afrikaans 1983/1992-vertaling"**, as the Bible Society names it.
|
||||
- **New per translation:** `acknowledgement` (the full notice, for the App's Acknowledgements
|
||||
page), `disclaimer` (the Bible Society's, required with its translations next to content it
|
||||
hasn't approved; null for the others), `publisher` and `permissionsUrl` (null for the KJV).
|
||||
- **`FREE_QUOTE_VERSES`** (500) and **`quotedVerses(passages)`**: verses quoted per translation,
|
||||
so the Hub and the App can warn before the free allowance runs out. `devotionalDisclaimer`.
|
||||
|
||||
## events@3.8.0 + @crosscode/demo 1.1.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Cross Events (docs/APP-1.0-PLAN.md §8 and §12). One migration.
|
||||
Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
- **Events 3.8.0:** STOP stops all WhatsApp (not only news), checked before every message, kept by
|
||||
number and per account (`whatsapp_opted_out` from Accounts), passed on to Accounts
|
||||
(`whatsapp.optout`); START turns it back on without Accounts. The eight demo scenarios
|
||||
(`set-demo.js --profile=<scenario>`), built around the scenario's own people and campuses.
|
||||
- **`@crosscode/demo` 1.1.0:** each person's `gender` (for Events' gendered events and cabins).
|
||||
- **crosscode script:** Events takes the scenarios as demo profiles; Events installs and builds
|
||||
`packages/demo`.
|
||||
|
||||
## accounts@1.9.0 + @crosscode/demo 1.0.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Accounts (docs/APP-1.0-PLAN.md §8 and §12). One migration. Details
|
||||
in `apps/accounts/CHANGELOG.md`.
|
||||
|
||||
- **Accounts 1.9.0:** `messaging.get` and the `messaging.changed` hint (the App sends with the
|
||||
church's one set of email and WhatsApp settings); the WhatsApp opt-out for every product
|
||||
(`whatsapp.optout`, its own WAWP webhook for a church without Events, `whatsapp_opted_out` in
|
||||
`user.updated`, "Turn WhatsApp back on" on the account page); a demo scenario's church profile,
|
||||
logo, icon and people (`npm run demo -- --profile <scenario> --force`).
|
||||
- **`@crosscode/demo` 1.0.0** (new, `packages/demo`, not tagged): the eight scenarios' churches,
|
||||
people (same `sub` in every product) and SVG logos, for every product's demo loader.
|
||||
- **crosscode script:** `crosscode demo <church> accounts --profile <scenario>` (backup, load,
|
||||
reload); `--scenario <s>` on every demo (the profile must be the scenario's); Accounts installs
|
||||
and builds `packages/demo`.
|
||||
|
||||
## contracts@1.21.0 - 2026-11-30
|
||||
|
||||
Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the
|
||||
Hub loads every product with the same church. Additive for `seed-demo` jobs older Hubs send.
|
||||
|
||||
- **`agent.DEMO_SCENARIOS`**: eight, one per Website demo profile and keyed by it, each its own
|
||||
fictional church (St Columba's, Grace Cathedral, Ignite Church, Harbour City, Acacia Hill, Karoo
|
||||
Gemeenskapskerk, Northpoint, Riverside) with a label, description, campuses, language, the App's
|
||||
active-member band, and the profile each product loads. `demoScenario(key)`,
|
||||
`DEMO_SCENARIO_ORDER` (Accounts, Events, Website, App), `DEMO_SCENARIO_MIN_VERSIONS` (Accounts
|
||||
1.9.0, Events 3.8.0, Website 1.8.0, App 1.0.0).
|
||||
- **`seed-demo`** takes an optional `scenario`; its `profile` must then be the scenario's for the
|
||||
product. `accounts` joins `DEMO_PRODUCTS` (the scenario's church profile, logo, icon and people;
|
||||
no `adminEmail`). Events gets a profile per scenario next to its four (`EVENTS_DEMO_PROFILES`),
|
||||
so a scenario name with no `product` is an Events demo.
|
||||
- **`APP_DEMO_PROFILES`** is the eight scenarios. 1.20.0's `acacia-hill` is gone: it's the
|
||||
`community-family` scenario, and no App or Hub had used it.
|
||||
- `SEED_SCENARIO_MIN_AGENT` (1.7.0) and `SEED_DEMO_MIN_AGENT_BY_PRODUCT`. JSON Schema `agent-job`
|
||||
regenerated.
|
||||
|
||||
## contracts@1.20.0 - 2026-11-30
|
||||
|
||||
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12), the first step of phase 6. Additive:
|
||||
products on 1.19.0 keep working. Accounts refuses the two new requests (`INVALID_REQUEST`) until
|
||||
Accounts 1.9.0 answers them.
|
||||
|
||||
- **`crosscode.devotional/1`** (`src/devotional.ts`): `devotionalSchema` (date, title, the passage
|
||||
with its text and translation, body, prayer, author, `source` `crosscode` or `church`),
|
||||
`devotionalsReplySchema` (the Hub's `GET /api/v2/devotionals?from=`, Cross Code's only),
|
||||
`CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3). **CSV import** shared by the Hub and the App:
|
||||
`DEVOTIONAL_CSV_COLUMNS`, `parseCsv` (quotes, line breaks, BOM, `;` files), `checkDevotionalCsv`
|
||||
(each row's errors by column, warnings, days already taken, a `latestDate` limit, dates twice in
|
||||
the file), `devotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`.
|
||||
- **Bible passages** (`src/bible.ts`): `BIBLE_TRANSLATIONS` (NLT, ESV, NIV, NKJV, KJV, AFR53, AFR83,
|
||||
each with its YouVersion id and copyright line), `BIBLE_BOOKS` (USFM codes, English and Afrikaans
|
||||
names, abbreviations, chapters), `parseBibleReference` ("Johannes 3:16–18", "1 Kor. 13:4-7",
|
||||
"Rom 8:38-9:1", "Jude 3"), `formatBibleReference`, `passageVerseCount`, `youVersionUrl`,
|
||||
`PASSAGE_WARN_VERSES` (25).
|
||||
- **Identity requests:** `messaging.get` (the church's SMTP and WAWP settings for the App, secrets
|
||||
sealed with the link's secret; `messagingGetReplySchema`) and the `messaging.changed` hint
|
||||
Accounts sends back (`MESSAGING_CHANGED_PATH`); `whatsapp.optout` (a STOP received by any
|
||||
product; `whatsappOptOutReplySchema`). `whatsapp_opted_out` (optional) in the profile that
|
||||
`user.updated` and the sign-in claims carry.
|
||||
- **App:** `APP_MODULES`; `hub.DEVOTIONALS_PATH` and its error codes; `agent.APP_DEMO_PROFILES`
|
||||
(`acacia-hill`), `app` in `DEMO_PRODUCTS`, `SEED_APP_DEMO_MIN_AGENT` (1.7.0, not released yet).
|
||||
- **Church export:** the `app` section (`exportAppSchema`: prayer wall rules, commitments as rules
|
||||
with their skips, "I prayed" marks, campaigns, testimonies, prayer requests with their
|
||||
moderation, emergency numbers, announcements, the church's own devotionals, simple events), and
|
||||
`people[].roles` (optional) for a person with several roles.
|
||||
- New samples: `devotionals-reply`, `messaging-get`, `messaging-get-reply`, `messaging-changed`,
|
||||
`whatsapp-optout`, `whatsapp-optout-reply`, `church-export-app`. New JSON Schemas: `devotional`,
|
||||
`devotionals-reply`, `messaging-get-reply`, `messaging-changed`, `whatsapp-optout-reply`.
|
||||
|
||||
## website@1.7.1 - 2026-11-28
|
||||
|
||||
Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only).
|
||||
One migration: a nullable `framing` column on `Ministry`, `Leader` and `SimpleEvent`. Details in
|
||||
`apps/website/CHANGELOG.md`.
|
||||
|
||||
## website@1.7.0 - 2026-11-27
|
||||
|
||||
Photos can be moved and zoomed in their frame, and unused photos deleted. Details in
|
||||
`apps/website/CHANGELOG.md`. No migration.
|
||||
|
||||
- **Move and zoom:** a section's photo shows in its frame's shape for the template and layout,
|
||||
with a dialog to drag and zoom it; saved with the section (`data.framing`), a draft until
|
||||
published.
|
||||
- **Delete photos:** the media library says where each photo is used, and deletes one used nowhere
|
||||
(its files too); `DELETE /api/v1/admin/media/:id` refuses one in use.
|
||||
|
||||
## events@3.7.2 + website@1.6.1 - 2026-11-27
|
||||
|
||||
Events shown on the other product's site no longer show twice after a reseed, and the Website's
|
||||
header marks the link to the Events site. Details in each app's CHANGELOG. No migrations.
|
||||
|
||||
- **Both:** the 15-minute event-feed poll and "Sync now" fetch the whole list and drop copies that
|
||||
aren't in it, so events a sibling lost without listing them in `deleted` (a reseed, a restore)
|
||||
can't stay beside the new ones. The fetch after an `event.changed` stays incremental.
|
||||
- **Events 3.7.2:** new demo data (`set-demo.js`) lists the old events as removed in the feed,
|
||||
publishes the new ones and tells the Website at once, and fetches the Website's events back in.
|
||||
- **Website 1.6.1:** loading a demo lists the old events as removed and tells Events; the header
|
||||
shows "Events site" with an external-link icon instead of a second "Events".
|
||||
|
||||
## website@1.6.0 - 2026-11-27
|
||||
|
||||
The demo church has real photos, and photos in small frames load at their size. Details in
|
||||
`apps/website/CHANGELOG.md`. No migration.
|
||||
|
||||
- **Demo photos:** 104 Unsplash stock photos (models, free under the Unsplash License, credited
|
||||
in `apps/website/backend/demo-photos/CREDITS.md`) instead of the generated illustration: a set
|
||||
per demo profile, a portrait for every leader, a picture for each event, and a photo for each
|
||||
message instead of the stand-in video's thumbnail. Loaded like uploads, in the responsive sizes.
|
||||
- **Faster on phones:** the collage hero, the team's portraits and the ministry cards give the
|
||||
browser their real width (`sizes`), so a phone no longer fetches the full-width photo for a
|
||||
small frame.
|
||||
|
||||
## website@1.5.0 + crosscode script - 2026-11-27
|
||||
|
||||
The Church Website's nightly backup also backs up the photos and files. Details in
|
||||
`apps/website/CHANGELOG.md`. No migration.
|
||||
|
||||
- **Website 1.5.0:** each night after the database, a snapshot of `backend/uploads` in
|
||||
`backend/backups/uploads-YYYYMMDD-HHMMSS/`; unchanged files are hard links to the last snapshot,
|
||||
so after the first full copy a night costs only the new files. On Admin → Backups, with its own
|
||||
switch. Kept to the same count as the database backups.
|
||||
- **crosscode script:** an uninstall keeps the Website's backups with `rsync -aH`, so the
|
||||
snapshots' shared files stay shared instead of each becoming a full copy.
|
||||
|
||||
## website@1.4.0 - 2026-11-27
|
||||
|
||||
Database backups and background jobs for the Church Website, as Accounts and Cross Events have.
|
||||
Details in `apps/website/CHANGELOG.md`. No migration (pg-boss makes its own `pgboss_website`
|
||||
schema on first start).
|
||||
|
||||
- **Backups:** a gzipped `pg_dump` every night at 02:20 into `backend/backups/`, the same
|
||||
`website-*.sql.gz` files the crosscode script makes before updates; Admin → Backups.
|
||||
- **Background jobs** on pg-boss: the backup, the Hub heartbeat, the event feed and YouTube (before:
|
||||
plain timers); Admin → Background jobs switches each on or off, changes its schedule, runs one now.
|
||||
- **The heartbeat tells the Hub the truth:** the newest backup (before: always none, so the Hub
|
||||
warned "No backup reported") and the real job mode and failures.
|
||||
|
||||
## contracts@1.19.0 + agent@1.6.0 + website@1.3.0 + crosscode script - 2026-11-27
|
||||
|
||||
Demo data for the Church Website, from the Hub (Hub 2.25.0). Additive: an Events `seed-demo` job
|
||||
means what it did. Details in each app's CHANGELOG.md. No migrations.
|
||||
|
||||
- **contracts 1.19.0:** `agent.WEBSITE_DEMO_PROFILES` (eight, two per template:
|
||||
`heritage-parish`, `heritage-city`, `bold-youth`, `bold-plant`, `community-family`,
|
||||
`community-town`, `clean-modern`, `clean-campus`), `DEMO_PRODUCTS`, `DEMO_PROFILES_BY_PRODUCT`,
|
||||
`SEED_WEBSITE_DEMO_MIN_AGENT` (1.6.0). `seed-demo` args take an optional `product` (`events`,
|
||||
the default, or `website`); the profile must be one of that product's, and a Website demo takes
|
||||
no `adminEmail`.
|
||||
- **agent 1.6.0:** a Website `seed-demo` job runs `crosscode demo <church> website --profile <p>`.
|
||||
- **website 1.3.0:** the eight demo churches (`backend/src/demo/seeds.ts`,
|
||||
`npm run demo -- --profile <p>`, `--list`). They replace the content only: the church's profile
|
||||
from Accounts, the site settings, the site icon and the admins stay, and the copy names the
|
||||
church. `--template` alone is still the Acacia Hill development church.
|
||||
- **crosscode script:** `crosscode demo <church> website --profile <p>`: backup, the demo as the
|
||||
site's user (`--force`), reload, wait for `/api/health`. Refused on a Website release without
|
||||
the profiles (before 1.3.0).
|
||||
|
||||
## accounts@1.8.0 + website@1.1.0 - 2026-11-26
|
||||
|
||||
The admins of both, redesigned as Cross Events' admin dashboard and settings. Details in each app's
|
||||
CHANGELOG.md. No migrations, no backend changes.
|
||||
|
||||
- **Accounts 1.8.0:** `/admin` is an overview (cards, "Needs you", a tile per section); People
|
||||
moved to `/admin/people`; the sidebar shows the part you're in, grouped; People redesigned.
|
||||
- **Website 1.1.0:** an icon sidebar in groups, a dashboard, steps to the first publish across the
|
||||
top, and a live preview beside the page editor and Template and style (drafts in a frame, no
|
||||
preview cookie).
|
||||
|
||||
## accounts@1.7.1 + website@1.0.2 + events@3.7.1 - 2026-11-26
|
||||
|
||||
Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations.
|
||||
|
||||
- **Linking right after an install** (all three): a connect involving an install that isn't in the
|
||||
cached copy of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at most once a
|
||||
minute) instead of refusing. Before, a new product and its siblings only learned of each other at
|
||||
their 15-minute heartbeats, so a new Website's admin couldn't sign in for up to 30 minutes.
|
||||
- **Accounts 1.7.1:** also a heartbeat on every start.
|
||||
- **Website 1.0.2:** opening `/admin` without a link to Accounts links on the spot; the problem page
|
||||
says "not linked yet" (`ACCOUNTS_NOT_LINKED`) instead of "can't reach your sign-in". Preview no
|
||||
longer redirects to the server's own `http://localhost:<web port>` (relative redirects).
|
||||
- **Events 3.7.1:** a new Website can connect for the event feed straight away.
|
||||
|
||||
## website@1.0.1 + crosscode script - 2026-11-26
|
||||
|
||||
Details in `apps/website/CHANGELOG.md`.
|
||||
|
||||
- **Website 1.0.1:** the messages' YouTube thumbnails are served from the site
|
||||
(`/api/thumbnails/<id>.jpg`), so visitors ask nothing of YouTube until they press play; the
|
||||
Calendar events' dates read "Sun · November", not "Sun (month: November)". No migration.
|
||||
- **crosscode script:** a Website's export leaves out `uploads/.thumbnails` (the kept thumbnails).
|
||||
|
||||
## contracts@1.18.0 - 2026-11-25
|
||||
|
||||
"Get more storage" for the Church Website (WEBSITE-1.0-PLAN §10, decision 12), with Hub 2.22.0.
|
||||
Additive: products on 1.17.0 keep working.
|
||||
|
||||
- **`hub.storageRequestSchema` / `storageRequestResponseSchema`**: a Website asks the Hub for more
|
||||
5 GB steps (`POST /api/installs/storage-request`, signed as the heartbeat), with what it uses,
|
||||
its limit and who asked. `hub.STORAGE_STEP_BYTES`. New sample `hub-storage-request.json` and
|
||||
JSON Schemas `hub-storage-request`, `hub-storage-request-response`.
|
||||
|
||||
## events@3.7.0 + @crosscode/ui 0.3.0 - 2026-11-24
|
||||
|
||||
Cross Events' public pages use the church's brand style and the shared footer (WEBSITE-1.0-PLAN §9).
|
||||
Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
- **Events 3.7.0:** the church profile from Accounts (`GET /api/v2/church`), its fonts and corners
|
||||
on the public pages, `ChurchFooter` and links to the church's other sites; `church.changed` is
|
||||
accepted at `/api/church/v1/changed`. Dashboard and setup unchanged. No migrations.
|
||||
- **`@crosscode/ui` 0.3.0:** `ChurchFooter` takes `bottom` (a product's own links).
|
||||
|
||||
## contracts@1.17.0 + accounts@1.7.0 + @crosscode/ui 0.2.0 - 2026-11-24
|
||||
|
||||
The first release of the Church Website 1.0.0 work (WEBSITE-1.0-PLAN §12). The contracts are
|
||||
additive and optional: products on 1.16.0 keep working. Accounts 1.7.0 ships with them because it
|
||||
answers the new `church.update` request. Details of Accounts in `apps/accounts/CHANGELOG.md`.
|
||||
|
||||
- **Brand style** (`./style`): the 8 font pairings confirmed on 2026-11-24 (`FONT_PAIRINGS`:
|
||||
`classic`, `scholarly`, `editorial`, `impact`, `contemporary`, `friendly`, `warm`, `modern`, each
|
||||
with its heading and body font), the corner styles (`CORNERS`, `DEFAULT_CORNERS` = `soft`), the
|
||||
Website's templates (`WEBSITE_TEMPLATES`) and the three pairings each recommends
|
||||
(`TEMPLATE_FONT_PAIRINGS`, default first). The ids are stored in profiles and never change.
|
||||
- **`crosscode.church/1`:** optional `branding.style` (`fontPairing`, `corners`, each nullable). An
|
||||
id a product doesn't know yet reads as null, so a newer Accounts never breaks an older product.
|
||||
- **`crosscode.church-export/1`:** an optional `website` part (template, first publish, style
|
||||
settings, pages with their sections, messages, simple events, the publish history's notes and
|
||||
the media library's alt text). New sample `church-export-website.json`.
|
||||
- **`church.update`** (identity request, product → Accounts, signed with the link's secret): the
|
||||
Website's admin changes shared profile facts (plan decision 10). The product checks the person's
|
||||
role and sends them as `actor`; only the fields given change (`branding` field by field); live at
|
||||
once, then `church.changed`. Optional `ifUpdatedAt` refuses with the new error code
|
||||
`PROFILE_CHANGED` when someone saved in between. Reply: the profile (`churchUpdateReplySchema`).
|
||||
Accounts 1.7.0 takes it from the Website only.
|
||||
- **Licence:** optional `limits.storageBytes`, the Website's storage limit including add-ons (plan
|
||||
decision 12). New sample `hub-licence-payload-website.json`.
|
||||
- **Accounts 1.7.0:** the brand style in Admin → Church profile, the church's fonts, corners and
|
||||
shared footer on its pages, and `church.update` from the Website. Update Accounts before (or with)
|
||||
anything that sends `church.update`; nothing does until the Website.
|
||||
- **`@crosscode/ui` 0.2.0:** `fonts.css` (the 8 pairings' fonts, Latin and Latin Extended, from the
|
||||
pinned `@fontsource-variable` packages, with Capsize size-matched fallbacks on Arial or Georgia;
|
||||
generated by `scripts/fonts.mjs`, checked by `npm test`, at most 160 KB per pairing for an
|
||||
English page), `brandAttributes`, `ChurchFooter`, `productLinks`; the components' corners follow
|
||||
`--cc-radius` and headings the pairing's heading font. Apps without a pairing look as before.
|
||||
- `package-lock.json` catches up with the agent's and contracts' versions.
|
||||
|
||||
## agent@1.5.0 + contracts@1.16.0 + crosscode script - 2026-11-23
|
||||
|
||||
- **Fix: uninstalling one product removed the whole church.** `crosscode uninstall <church>` only
|
||||
knew whole churches, while the Hub uninstalls per product: uninstalling cross-events-demo's
|
||||
Events also removed its Accounts, which the Hub still showed as live, and its own uninstall
|
||||
failed later ("No church cross-events-demo on this server").
|
||||
- **`crosscode uninstall|export|purge <church> [product …]`.** With products named, only those
|
||||
are backed up, kept (`.removed/<church>-<date>/<product>`) and removed; the church keeps the
|
||||
others in church.env. Naming every product it still has removes the church (folder and app
|
||||
user), so the last product to go always takes the church with it. The report gives `products`
|
||||
and `remaining`. `purge` with products deletes only what was kept of those, also while the
|
||||
church still has others. Without products, as before.
|
||||
- **Agent 1.5.0** passes `products` through. **Contracts 1.16.0:** optional `products` on the
|
||||
`export`, `uninstall` and `purge` job arguments, and `PRODUCT_UNINSTALL_MIN_AGENT` (an older
|
||||
agent refuses the key). Hub 2.12.0 uses them.
|
||||
- The Church Website plan's versions move up one again: contracts 1.17.0, Hub 2.13.0.
|
||||
|
||||
## agent@1.4.0 + contracts@1.15.0 - 2026-11-21
|
||||
|
||||
- **Agent 1.4.0: frp's config, wherever it is.** The agent no longer assumes
|
||||
`/etc/frp/frps.ini`: it uses the path set on the Hub, else the `-c` in the frps/frpc systemd
|
||||
unit, else the usual places (`/etc/frp`, `/usr/local/frp`, `/opt/frp` …), and reads TOML
|
||||
(`proxyBindAddr`, `allowPorts = [{ start, end }]`) as well as INI. The central server's check
|
||||
after an install failed with "No frps.ini at /etc/frp/frps.ini" on a server that keeps it
|
||||
elsewhere. Stats say which file it uses (`frpConfigPath`). `crosscode` gets `FRPC_INI` for it
|
||||
on church servers.
|
||||
- **New jobs** (both modes): `frp-read` (the config, secrets hidden), `frp-write` (secrets put
|
||||
back, `frp* verify`, backup, restart, the old file back if frp doesn't start) and
|
||||
`probe-ports` (which of these ports are free here). Contracts 1.15.0: the job arguments,
|
||||
`frpReadResultSchema`, `probePortsResultSchema`, `FRP_JOBS_MIN_AGENT`, `FRP_HIDDEN`,
|
||||
`agentStats.frpConfigPath`. The Hub needs agent 1.4.0 on a server for these (Hub 2.11.0).
|
||||
- The Church Website plan's versions move up one: contracts 1.16.0, Hub 2.12.0.
|
||||
|
||||
## crosscode script - 2026-11-20 (no tag: servers run `main`)
|
||||
|
||||
- **Fix:** the database dump made before each Accounts deploy (`apps/accounts/backend/backups/`)
|
||||
counted as a file added by hand on Accounts below 1.3.0 (no `.gitignore` for it yet), so the
|
||||
next deploy stopped with "changed or added by hand". Untracked files in that folder no longer
|
||||
count (`CROSSCODE_OWN_DIRS` in `lib/common.sh`).
|
||||
|
||||
## events@3.6.1 - 2026-11-20
|
||||
|
||||
- **Events 3.6.1 (fix):** uploading a logo or favicon failed with "uploaded, but the site can't
|
||||
show it yet" behind a proxy with a file-extension rule (FastPanel's static-file handling sent
|
||||
`/api/uploads/…png` to the frontend). The site now passes `/api/*` and `/uploads/*` that reach
|
||||
it on to the backend (new `BACKEND_INTERNAL_URL`, added on deploy).
|
||||
- **crosscode script:** the nginx site it writes uses `location ^~ /api/` and `^~ /uploads/`.
|
||||
|
||||
## accounts@1.6.0 - 2026-11-20
|
||||
|
||||
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp for a verified number) after every
|
||||
sign-in, as Cross Events' own sign-in did; Sign-in settings → `signin_notices` turns it off.
|
||||
|
||||
## events@3.6.0, accounts@1.5.0, contracts@1.14.0 - 2026-11-20
|
||||
|
||||
A nightly check that each site's copies of people match their church accounts, for changes that
|
||||
never arrived.
|
||||
|
||||
- **Contracts 1.14.0:** `people.check` in `crosscode.identity-request/1` (`PEOPLE_CHECK_MAX` 500)
|
||||
and `peopleCheckReplySchema` (each sub `active` / `deactivated` / `deleted` / `unknown`, with the
|
||||
profile for the first two). Samples and JSON Schema `people-check-reply`.
|
||||
- **Accounts 1.5.0:** answers it, only with profiles of people the product knows.
|
||||
- **Events 3.6.0:** the `accounts-people-check` job (04:30): fixes out-of-date copies, handles
|
||||
deleted accounts as `user.deleted`, and stops if most people are unknown (wrong Accounts?).
|
||||
|
||||
## events@3.5.0, contracts@1.13.0, agent@1.3.1 - 2026-11-20
|
||||
|
||||
- **Agent 1.3.1:** agent 1.3.0 still reported itself as 1.2.0 (`AGENT_VERSION` in `src/stats.ts`
|
||||
wasn't bumped with `package.json`), so the Hub refused `.env` jobs on it. Use 1.3.1.
|
||||
|
||||
Loading demo data left a site that signs in through Accounts with no Accounts link, so nobody could
|
||||
sign in (`ACCOUNTS_UNAVAILABLE`, found on events-demo). The Hub (2.9.0) now sees it.
|
||||
|
||||
- **Contracts 1.13.0:** `stats.signIn` in the Cross Events heartbeat (mode, the linked Accounts,
|
||||
the last sign-in failure; optional).
|
||||
- **Events 3.5.0:** `set-demo.js` keeps `ProductLink` and `LinkNonce`; a site in Accounts mode
|
||||
without a link reconnects at its next heartbeat even after an earlier auto-connect; sign-in
|
||||
failures (start, finish, Accounts unreachable) are kept and sent to the Hub; What's New notes for
|
||||
3.4.0 (and Accounts 1.4.0) that were missing.
|
||||
|
||||
## events@3.4.0, accounts@1.4.0, contracts@1.12.0, agent@1.3.0, crosscode script - 2026-11-20
|
||||
|
||||
Background jobs are switched on and off (and rescheduled) from each site's admin, over the .env;
|
||||
Accounts' emails look like Cross Events'; the Hub shows and changes an install's .env (Hub 2.8.0).
|
||||
|
||||
- **Contracts 1.12.0:** `env-read` and `env-set` agent jobs, `envReadResultSchema`,
|
||||
`isSecretEnvName` / `SECRET_ENV_NAME`, `ENV_JOBS_MIN_AGENT` (1.3.0). `env-set` refuses secrets,
|
||||
newlines, files other than `backend/.env` / `frontend/.env.production`, and empty changes.
|
||||
- **crosscode script:** `crosscode env <church> <product>` prints the product's .env values
|
||||
(secrets only as set or not); with `--set NAME=value`, `--unset NAME` and `--restart` it changes
|
||||
one file (a copy is kept, the last 5), rebuilds the frontend when its file changed, reloads, and
|
||||
waits for `/health`; if that fails the file is put back (and rebuilt). Secrets and generated
|
||||
values are refused (`lib/envedit.cjs`). Tests: `scripts/tests/envedit.bats`.
|
||||
- **Agent 1.3.0:** runs `env-read` and `env-set` as `crosscode env`.
|
||||
- **Events 3.4.0:** Settings → Background jobs switches each job on or off and changes its
|
||||
schedule; the choice is kept in the database, wins over the .env and applies straight away.
|
||||
- **Accounts 1.4.0:** Admin → Background jobs (the same as Events'); every email is styled as
|
||||
Cross Events' (church colour and logo, a button, contact details), with the same plain text.
|
||||
|
||||
## events@3.3.0, accounts@1.3.0, contracts@1.11.0 - 2026-11-20
|
||||
|
||||
Accounts looks like Cross Events and backs itself up; fixes in Events' sign-out and branding uploads.
|
||||
|
||||
- **Contracts 1.11.0:** `people.removeDemo` in `crosscode.identity-request/1` (and its reply):
|
||||
new demo data in a product removes the old demo people's accounts. Only `@example.com` addresses
|
||||
(`DEMO_EMAIL_DOMAIN`), never an Accounts admin.
|
||||
- **Accounts 1.3.0:** the account and admin pages in Cross Events' layout (top bar, sidebar of
|
||||
sections with their own addresses, dark footer); quick links to the church's sites; nightly
|
||||
database backups with an admin Backups page; a fuller built-in privacy notice; its own favicon.
|
||||
- **Events 3.3.0:** signing out also signs out of Accounts; uploaded logos and favicons are served
|
||||
from the folder they're saved in; new demo data replaces the old demo people in Accounts.
|
||||
|
||||
## events@3.2.0, contracts@1.10.0 - 2026-11-19
|
||||
|
||||
Emergency updates can run as soon as possible (Hub 2.7.0); the Hub asks again when an event is on.
|
||||
|
||||
- **Contracts 1.10.0:** `stats.live` in the Cross Events heartbeat (`eventsNow`, `checkInsLastHour`;
|
||||
optional).
|
||||
- **Events 3.2.0:** sends it (sessions or one-day events on now, check-ins in the last hour).
|
||||
|
||||
## events@3.1.0, accounts@1.2.0, contracts@1.9.0 - 2026-11-19
|
||||
|
||||
A church moved Cross Events' sign-in to Accounts without email set up in Accounts: Accounts couldn't
|
||||
send codes or password links, sign-in failed with a 500, and nobody could get in.
|
||||
|
||||
- **Contracts 1.9.0:** `messaging.status`, `messaging.test`, `messaging.set` in
|
||||
`crosscode.identity-request/1` (SMTP and WAWP settings, secrets sealed); `people.ensure` answers
|
||||
`emailSent`.
|
||||
- **Accounts 1.2.0:** a code or link that can't be sent shows a message instead of a 500 (WhatsApp
|
||||
codes fall back to email); forgot password says email isn't set up; the `messaging.*` requests
|
||||
(test, and save only what worked); a test WhatsApp in its admin; WAWP from the `.env` too.
|
||||
- **The sign-in pages look like the church's site:** `@crosscode/ui` Shell / Card / Heading redone
|
||||
(colour wash, logo and name, cards edged in the church's colour, icons); Events sends its logo and
|
||||
colours (`church.branding`, and with a move).
|
||||
- **Events 3.1.0:** Settings → Sign-in shows what Accounts can send and sets it up by copying this
|
||||
site's SMTP / WAWP (its secrets stay on the server), with a test before saving; the move needs
|
||||
Accounts' email (disabled, and refused by the server, without it).
|
||||
|
||||
## crosscode script - 2026-11-19 (no tag: servers run `main`)
|
||||
|
||||
- **A church with Accounts couldn't be updated.** `crosscode install` / `add` writes Accounts' PM2
|
||||
config to `apps/accounts/ecosystem.config.cjs`, which no `.gitignore` covered, so the next
|
||||
`deploy` stopped at "files … were changed or added by hand: ?? apps/accounts/ecosystem.config.cjs".
|
||||
The PM2 configs crosscode makes (`apps/events/ecosystem.config.js`, `apps/accounts/ecosystem.config.cjs`)
|
||||
no longer count as changes by hand, also in checkouts of releases that don't ignore them, and
|
||||
`apps/accounts/.gitignore` ignores it from the next Accounts release on. bats test.
|
||||
|
||||
## events@3.0.0, accounts@1.1.0, contracts@1.8.0, crosscode script - 2026-11-19
|
||||
|
||||
Cross Events signs in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md).
|
||||
|
||||
@@ -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) |
|
||||
| `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)
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -1,5 +1,241 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.9.0] - 2026-11-30
|
||||
|
||||
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
|
||||
`crosscode` script on `main` builds it). **One migration** (`20261130000000_accounts_1_9`): two
|
||||
columns on `Account`, one on `ProductLink`, a `WhatsAppOptOut` table. No new .env variables. Part of
|
||||
Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
|
||||
|
||||
### Added
|
||||
|
||||
- **`messaging.get`** (contracts 1.20.0): a linked product gets the church's email (SMTP) and
|
||||
WhatsApp (WAWP) settings, the password and token sealed with the link's secret, and is
|
||||
remembered (`ProductLink.messagingWantedAt`). The reply is never kept in `ProductRequest`.
|
||||
- **`messaging.changed`**: when an admin changes the email or WhatsApp settings here, or a product
|
||||
saves them (`messaging.set`), each product that asked is sent the hint at
|
||||
`/api/accounts/v1/messaging-changed` (a `Delivery`, retried as the other calls), except the one
|
||||
that made the change.
|
||||
- **The WhatsApp opt-out for every product** (APP-1.0-PLAN decision 11):
|
||||
- `whatsapp.optout` from a product that received a STOP: the number is kept (`WhatsAppOptOut`),
|
||||
every account with it is opted out (`Account.whatsappOptedOut`), its news on WhatsApp turned
|
||||
off (a consent change, `whatsapp_stop`), and `user.updated` goes to every product with
|
||||
`whatsapp_opted_out: true`. A number without an account is kept too: an account that gets it
|
||||
later (sign-up, the account page, `people.ensure`, `people.update`, an import) starts opted out.
|
||||
- **Accounts' own WAWP webhook**, `POST /api/v2/webhooks/whatsapp?secret=…`, for a church without
|
||||
Cross Events: a STOP (English or Afrikaans: STOP, STOPP, UNSUBSCRIBE, OPT OUT, UITTEKEN) opts
|
||||
the number out and answers once with how to undo it. Admin → Email and WhatsApp → **WhatsApp
|
||||
replies (STOP)** shows the address to give WAWP and when it last called (or that Cross Events
|
||||
takes the replies).
|
||||
- Accounts sends an opted-out person no WhatsApp: sign-in codes go by email, setting WhatsApp up
|
||||
as the two-step method is refused, sign-in notices skip it.
|
||||
- **Turn WhatsApp back on** on the account page (Privacy), `POST /api/v2/me/whatsapp-on`: the
|
||||
number's STOP is forgotten and the products are told. News on WhatsApp stays off until ticked.
|
||||
- "Download my data" shows whether WhatsApp is off and since when.
|
||||
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12), for demo sites only:
|
||||
- `npm run demo -- --profile <scenario> --force` (`--list` for the eight), run by
|
||||
`crosscode demo <church> accounts --profile <scenario>` after a backup. The church profile
|
||||
becomes the scenario's church (name, short name, locale, colours, font pairing, corners,
|
||||
campuses, service times, contact, social links), and `church.changed` goes to the products.
|
||||
- Its **logo and icon**, drawn for the demo (`@crosscode/demo`), at
|
||||
`/api/demo-assets/<scenario>/logo.svg` and `icon.svg`.
|
||||
- Its **people** (54 to about 2 450, enough for the scenario's App band), at example.com with the
|
||||
password `Demo@1234`, each with the same account id on every load and in every product
|
||||
(`demoId`). Demo people from another scenario are anonymised; real people (any other address)
|
||||
and Accounts admins are never touched; loading a scenario again brings its people back with
|
||||
their ids.
|
||||
|
||||
### Checked on PostgreSQL 18
|
||||
|
||||
All three migrations on an empty database (the result matches the schema exactly); scenario loads
|
||||
(Acacia Hill 0.8 s, Riverside's 2 457 people 3.4 s, switching back 14.7 s), the people's ids kept,
|
||||
a real person untouched; the STOP opt-out, a known number on a new account, turning it back on;
|
||||
`messaging.changed` queued; `npm run demo` with and without `--force`.
|
||||
|
||||
## [1.8.0] - 2026-11-26
|
||||
|
||||
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
|
||||
dashboard and settings.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`/admin` is an overview:** four cards (people with an account, deletion requests waiting,
|
||||
sites that sign in here, last backup), a "Needs you" list with buttons to act, and a tile with a
|
||||
line about every section. **People moved to `/admin/people`.**
|
||||
- **The sidebar shows the part you're in** (your account or admin, with a link to the other), and
|
||||
admin's sections are grouped: People, Church, Signing in, System. Deletion requests shows how many
|
||||
are waiting. The phone menu shows both parts. Every page title has its section's icon.
|
||||
- **People:** a search box, a row per person with initials, admin and status badges, two-step
|
||||
sign-in and last sign-in; the person's card stays in view while scrolling. Deactivating someone
|
||||
asks to confirm first.
|
||||
- **Email and WhatsApp** are two cards, each with its own Save.
|
||||
- Group labels are a darker grey (WCAG AA contrast).
|
||||
|
||||
## [1.7.1] - 2026-11-26
|
||||
|
||||
No migrations, no new settings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A product installed after Accounts' last heartbeat links straight away.** Accounts accepted a
|
||||
connect only from installs in its cached copy of the Hub's list, which it refreshed every 15
|
||||
minutes. A new Church Website (or Events) was refused ("doesn't know that install yet") and tried
|
||||
again only at its own next heartbeat, so its admin couldn't sign in for up to 30 minutes after the
|
||||
install (found on cross-demo2). Now, for an install it doesn't know, Accounts sends the Hub a
|
||||
heartbeat to get a fresh list and looks again (at most one such heartbeat a minute, so unknown
|
||||
installs can't make it call the Hub more often). The same applies when an Accounts admin connects.
|
||||
- **A heartbeat on every start**, not only the first: after a restart the list of the church's
|
||||
products is fresh at once.
|
||||
|
||||
## [1.7.0] - 2026-11-24
|
||||
|
||||
Needs contracts 1.17.0. The first part of the Church Website 1.0.0 (WEBSITE-1.0-PLAN §11).
|
||||
|
||||
### Added
|
||||
|
||||
- **Brand style** in the church profile (`branding.style`: font pairing and corners, contracts
|
||||
1.17.0). Admin → Church profile → **Brand style** shows each of the 8 pairings in its own fonts,
|
||||
and the three corner styles. Served in `GET /api/church/v1` and `/api/v2/branding`.
|
||||
- **The church's fonts and corners on Accounts' pages**: `@crosscode/ui/fonts.css` (self-hosted, no
|
||||
font requests to anyone else) and `brandAttributes` on `<html>`. Without a pairing the pages
|
||||
keep the device fonts, so nothing changes until an admin picks one.
|
||||
- **The shared footer** (`ChurchFooter` from `@crosscode/ui`) on the public pages (sign in, forgot
|
||||
and reset password, signed out, confirm email): service times, address, contact, social links,
|
||||
links to the church's other sites and the privacy notice, from the church profile.
|
||||
- **`church.update`** (contracts 1.17.0): the church's Website changes shared profile facts for its
|
||||
admins (WEBSITE-1.0-PLAN decision 10). Only from a product linked as `website`
|
||||
(`WRONG_PRODUCT`), only for an `actor` who signs in through it (`NOT_ALLOWED`), and refused
|
||||
with `PROFILE_CHANGED` (409) when `ifUpdatedAt` is out of date. Live at once; linked products get
|
||||
`church.changed`; audited as `church_profile_changed_by_product` with the fields changed.
|
||||
|
||||
### Changed
|
||||
|
||||
- Saving the profile merges `branding` field by field (`mergeProfile`), so a form or product that
|
||||
sends only part of it (the colours without the style, or only the style) never drops the rest.
|
||||
|
||||
## [1.6.0] - 2026-11-20
|
||||
|
||||
### Added
|
||||
|
||||
- **"New sign-in" notices**, as Cross Events' own sign-in sends (`src/accounts/signInNotice.ts`):
|
||||
after each completed sign-in (the interaction reaching done, so not the silent ones a second
|
||||
product gets from an existing session), an email with when, the site, rough location and device
|
||||
(`newSignInEmail` in `src/lib/emails.ts`), and a WhatsApp message when the person has a verified
|
||||
number and WhatsApp is set up. Location from ip-api.com in production only, never for private
|
||||
addresses. Fire-and-forget: never holds up or fails a sign-in. Admins can turn it off:
|
||||
`signin_notices` (Sign-in settings, on by default). In Accounts mode Cross Events no longer sends
|
||||
its own, so before this nobody was told.
|
||||
|
||||
## [1.5.0] - 2026-11-20
|
||||
|
||||
Needs contracts 1.14.0.
|
||||
|
||||
### Added
|
||||
|
||||
- `people.check` (contracts 1.14.0): for up to 500 subs, the current profile of each person the
|
||||
product knows (`active` / `deactivated`), `deleted` for a deleted account, `unknown` for anyone
|
||||
else (no profile). Audited once per request (`people_checked_by_product`, counts only); the reply
|
||||
isn't stored for retries, since it holds profiles. Cross Events 3.6.0 asks nightly.
|
||||
|
||||
## [1.4.0] - 2026-11-20
|
||||
|
||||
Works with every Cross Events 3.x and contracts 1.11.0 or later.
|
||||
|
||||
### Added
|
||||
|
||||
- **Admin → Background jobs**, as Cross Events': each job's schedule, next run and last runs,
|
||||
"Run now", and a switch and schedule per job. The choice is saved in the database
|
||||
(`job_overrides`), wins over the .env and applies straight away (other processes within 30 s).
|
||||
New optional .env flags per job, as Events: `EXPORTS_JOB_ENABLED`, `DELETIONS_JOB_ENABLED`,
|
||||
`BACKUP_ENABLED`, `HUB_HEARTBEAT_ENABLED`, and `JOB_SCHEDULE_<NAME>`. API: `GET /api/v2/admin/jobs`,
|
||||
`PUT /api/v2/admin/jobs/:name` `{ enabled, cron }`, `POST /api/v2/admin/jobs/:name/run`.
|
||||
On timers (when the queue can't start) jobs now follow their cron schedule too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Every email is styled as Cross Events'** (`src/lib/emails.ts`): a header in the church's
|
||||
colour with its logo or name, a button for the link (written out underneath), callouts for
|
||||
warnings, and the church's contact details in the footer. Sign-in codes, password reset, "your
|
||||
account at …", confirm a new email address, "your email address changed", "your data is ready"
|
||||
and the test emails. The plain text is sent too and hasn't changed. Everything put in the HTML is
|
||||
escaped, and only http(s) links are used.
|
||||
|
||||
## [1.3.0] - 2026-11-20
|
||||
|
||||
Needs contracts 1.11.0 (`people.removeDemo`). Works with every Cross Events 3.x.
|
||||
|
||||
### Added
|
||||
|
||||
- **Backups** (Admin → Backups, `src/backups/backups.ts`): a gzipped `pg_dump` every night at
|
||||
02:00 (job `backup`) and on "Back up now", into `backend/backups/` with the names the
|
||||
`crosscode` script already gives its pre-deploy dumps (`accounts-YYYYMMDD-HHMMSS.sql.gz`), so
|
||||
both show in one list. Keeps the newest 14 by default (`backup_retain_count`), nightly can be
|
||||
turned off (`backup_nightly`), downloads are admin-only and audited, a failed dump leaves no file
|
||||
and shows why (`backup_last_error`). The heartbeat's `lastBackupAt` is the newest backup.
|
||||
Needs `pg_dump` (the PostgreSQL client) on the server, as the crosscode script does.
|
||||
- **Quick links to the church's sites** on the account page (`GET /api/v2/me/apps`): each
|
||||
connected product; Events opens its dashboard through its own sign-in (no second sign-in).
|
||||
- `people.removeDemo` (contracts 1.11.0): a product's old demo people (`@example.com`, known
|
||||
through that product, not admins) are signed out everywhere and anonymised; the reply says which
|
||||
were kept and why.
|
||||
- A favicon (`app/icon.svg`), the same for every church.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The account and admin pages look like Cross Events' dashboard:** the church's logo and name in
|
||||
a top bar, a sidebar with the person, their role and the sections, panels with icon tiles, and a
|
||||
dark footer. Each section has its own address: `/account` (overview), `/account/details`,
|
||||
`/security`, `/privacy`, `/activity`; `/admin` (people), `/admin/deletions`, `/church`,
|
||||
`/linked`, `/signin`, `/messages`, `/notice`, `/backups`, `/licence`, `/audit`. The
|
||||
"your data is ready" email's link (`/account/privacy`) now opens the right section. Sign-in pages
|
||||
keep their centred card.
|
||||
- **The built-in privacy notice** is rewritten in sections, as Cross Events' policy: what's kept,
|
||||
how it's used, who sees it (the church's sites, admins, email and WhatsApp providers, aggregate
|
||||
totals to Cross Code), where and how long (including backups), cookies, POPIA rights, children,
|
||||
changes and contact. A line starting "## " is a heading and "• " a bullet, on the privacy page,
|
||||
the sign-in step and the admin's preview. Churches still on the built-in notice see the new text
|
||||
as version 1 (it describes the same practice more fully); Admin → Privacy notice can start a new
|
||||
version from it, which asks everyone to read it again.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `backend/.gitignore` ignores `/backups/` (the dumps the crosscode script makes).
|
||||
## [1.2.0] - 2026-11-19
|
||||
|
||||
Found after a church moved Cross Events' sign-in here without email set up in Accounts: every
|
||||
sign-in that needed an emailed code failed with a 500, and nobody could get in.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A code that can't be sent no longer fails the sign-in (500).** The page says the church's email
|
||||
isn't working and to tell the office (`CODE_NOT_SENT`, 503). A WhatsApp sign-in code that can't go
|
||||
is sent by email instead (as Cross Events); setting WhatsApp up still needs WhatsApp to work.
|
||||
- **Forgot password** says plainly that email isn't set up (`EMAIL_NOT_READY`, the same for every
|
||||
address) instead of failing.
|
||||
- Setting up two-step sign-in only offers email when email works (an app always does).
|
||||
- `people.ensure` makes the account even when its "choose your password" email can't go, and tells
|
||||
the product (`emailSent: false`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The sign-in pages look like the church's other sites:** a wash of the church's colour, its logo
|
||||
and name across the top (its first letter on its colour while there's no logo), the form in a card
|
||||
edged in that colour with an icon per step, and a footer (`@crosscode/ui` Shell, Card, Heading,
|
||||
ChurchMark; the account and admin pages get the same frame).
|
||||
- **The church's logo and colours come from Cross Events:** a move fills the logo, colours and name
|
||||
Accounts doesn't have yet (`import.begin` now carries the logo and accent colour), and
|
||||
`church.branding` (contracts 1.9.0) replaces them when an admin asks.
|
||||
|
||||
### Added
|
||||
|
||||
- **`messaging.*` requests** (contracts 1.9.0) for a linked product's sign-in settings: `status`
|
||||
(what can be sent, no secrets), `test` (sends a test email / WhatsApp with the settings given,
|
||||
saves nothing) and `set` (tests, then saves each part only if its test worked). The SMTP password
|
||||
and WAWP token come sealed with the link's secret, are stored encrypted, and `null` keeps the saved one.
|
||||
- Admin → Email and WhatsApp: **Send a test WhatsApp** (to the admin's own phone), next to the test email.
|
||||
- WAWP from the server's `.env` (`WAWP_ACCESS_TOKEN`, `WAWP_INSTANCE_ID`) when the database has
|
||||
none, as Cross Events and as SMTP already did.
|
||||
|
||||
## [1.1.0] - 2026-11-19
|
||||
|
||||
For Cross Events 3.0 (docs/EVENTS-3.0-PLAN.md §8), with contracts 1.8.0.
|
||||
|
||||
@@ -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,81 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.9.0
|
||||
|
||||
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
|
||||
WhatsApp from any of your church's sites any more, reminders and sign-in codes included (codes
|
||||
come by email instead). They can turn WhatsApp back on from their account page. Without Cross
|
||||
Events, Admin → Email and WhatsApp shows the address to give WAWP, so the replies reach Accounts.
|
||||
- Getting ready for the **Church App**: it will send with the email and WhatsApp settings you
|
||||
already have, without asking for its own, and pick up any change you make here.
|
||||
- **Demo churches** for Cross Code's demo sites: a church's name, logo, colours, service times and
|
||||
people for each of eight demo scenarios. Never used on a real church's sign-in.
|
||||
|
||||
## 1.8.0
|
||||
|
||||
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that
|
||||
needs you (like deletion requests waiting), and a tile for every setting. The menu down the side
|
||||
is grouped and shows only the part you're in. People has moved to Admin → **People**, with a
|
||||
search box and a clearer list; deactivating someone now asks you to confirm.
|
||||
|
||||
## 1.7.1
|
||||
|
||||
- **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed
|
||||
for your church can be signed in to within moments, instead of after up to half an hour.
|
||||
|
||||
## 1.7.0
|
||||
|
||||
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
|
||||
pairings, each shown in its own fonts, and sharp, soft or round corners. Your sign-in pages use
|
||||
them now, and your new Church Website and Cross Events' public pages will too, so all your sites
|
||||
look like one church. Until you pick, nothing changes.
|
||||
- **A footer with your church's details** under the sign-in pages: service times, address, contact
|
||||
details and links to your church's other sites, from the church profile.
|
||||
- Getting ready for the **Church Website**: its admins will be able to change your service times,
|
||||
logo and contact details from the website, and they'll change everywhere at once.
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- **You're told about each sign-in.** After someone signs in, they get an email saying when, roughly
|
||||
where, on what device and to which site, with what to do if it wasn't them, as Cross Events
|
||||
does for its own sign-in. People with a confirmed WhatsApp number get it on WhatsApp too.
|
||||
Admins can turn this off under Sign-in settings.
|
||||
|
||||
## 1.5.0
|
||||
|
||||
- Your church's sites can now check every night that the details they keep for each person match
|
||||
their church account (Cross Events 3.6.0 does), so a change that didn't reach a site is fixed the
|
||||
next morning.
|
||||
|
||||
## 1.4.0
|
||||
|
||||
- **Better-looking emails.** Sign-in codes, password links, "your account is ready" and the other
|
||||
emails from your church account now look like Cross Events' emails: your church's colour and logo
|
||||
at the top, a clear button, and your church's contact details at the bottom.
|
||||
- Admins: **Admin → Background jobs** shows what Accounts does on a schedule (backups, privacy
|
||||
requests, tidying up), when it last ran, and lets you run a job now, switch it off or change when
|
||||
it runs.
|
||||
|
||||
## 1.3.0
|
||||
|
||||
- Your account and the admin pages have a new look, like Cross Events: a menu down the side, and
|
||||
each part on its own page.
|
||||
- Quick links on your account page take you straight to the church's sites, already signed in.
|
||||
- Admins: the sign-in database is backed up every night, and backups can be made and downloaded
|
||||
under Admin → Backups.
|
||||
- A clearer privacy notice that says exactly what your church account keeps and why.
|
||||
- Accounts has its own icon in the browser tab.
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- **Fix:** when the church's email isn't working, signing in tells people so (and to let the office
|
||||
know) instead of showing an error page. Codes by WhatsApp are sent by email if WhatsApp is down.
|
||||
- Email and WhatsApp for sign-in can be set up from Cross Events (Settings → Sign-in), copying its
|
||||
own settings, with a test before they're saved.
|
||||
- Admins can send a test WhatsApp message from Email and WhatsApp.
|
||||
- **A nicer sign-in page** with your church's logo and colours, taken from Cross Events.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- **Ready for Cross Events 3.0:** Cross Events can move its people into your church's accounts,
|
||||
|
||||
@@ -4,3 +4,4 @@ src/generated/
|
||||
.env
|
||||
uploads/
|
||||
exports/
|
||||
/backups/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.1.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,14 +14,17 @@
|
||||
"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",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cron-parser": "^5.10.2",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"express-rate-limit": "^8.6.2",
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import { hashToken, randomCode, safeEqual } from '../lib/crypto.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { queueCall } from '../links/deliveries.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { SendError } from '../lib/messages.js';
|
||||
import { codeEmail } from '../lib/emails.js';
|
||||
|
||||
export const MAX_FAILED_SIGN_INS = 10;
|
||||
export const LOCK_MINUTES = 15;
|
||||
@@ -42,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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -100,18 +104,37 @@ export function maskedTarget(a: Account, method: 'email' | 'whatsapp'): string {
|
||||
return `${user!.slice(0, 1)}***@${domain}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a code. 1.2.0: a WhatsApp code that can't go is sent by email instead (as Cross Events), and
|
||||
* when nothing can send it the person is told so (`SendError`, shown on the page) instead of the
|
||||
* sign-in failing.
|
||||
*/
|
||||
export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp', purpose: 'sign_in' | 'verify_email' | 'setup'): Promise<{ codeHash: string; sentTo: string }> {
|
||||
const code = randomCode();
|
||||
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') {
|
||||
if (!a.phone) throw new Error('There\'s no phone number on this account.');
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
} else {
|
||||
await ctx.messenger.email({ to: a.email, subject: `Your code: ${code}`, text });
|
||||
// 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');
|
||||
}
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, method) };
|
||||
if (method === 'whatsapp' && a.phone && !a.whatsappOptedOut) {
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
|
||||
} catch (e) {
|
||||
// Setting WhatsApp up has to prove WhatsApp works, so no email instead then.
|
||||
if (purpose !== 'sign_in') throw new SendError('We couldn\'t send a code by WhatsApp. Choose another way to get your codes.', 'CODE_NOT_SENT');
|
||||
console.warn('[codes] WhatsApp failed, trying email:', (e as Error).message);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, ...(await codeEmail(ctx, { name: a.name, code, text, purpose, minutes: CODE_MINUTES })) });
|
||||
} catch (e) {
|
||||
console.error('[codes] could not send a code:', (e as Error).message);
|
||||
throw new SendError(`We couldn't send your code: ${churchName}'s email isn't working right now. Please let the church office know, and try again later.`, 'CODE_NOT_SENT');
|
||||
}
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'email') };
|
||||
}
|
||||
|
||||
export const codeMatches = (code: unknown, hash: string | null | undefined) =>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* "New sign-in" notices (1.6.0), as Cross Events sends for its own sign-in: after each completed
|
||||
* sign-in, an email to the person, and a WhatsApp message too when they have a verified number and
|
||||
* WhatsApp is set up. Admins can turn them off (Sign-in settings, `signin_notices`). Never holds up
|
||||
* or fails the sign-in.
|
||||
*
|
||||
* The rough location comes from the IP (ip-api.com, as Cross Events), in production only, and never
|
||||
* for private addresses.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { newSignInEmail } from '../lib/emails.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
|
||||
const PRIVATE_IP = /^(::1$|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|fc|fd|fe80|::ffff:(127|10|192\.168)\.)/i;
|
||||
|
||||
/** "Chrome on Windows" from a user agent; the raw string when it can't tell. */
|
||||
export function describeDevice(ua: string | null | undefined): string {
|
||||
const s = String(ua || '');
|
||||
if (!s) return 'Unknown device';
|
||||
const browser = /Edg\//.test(s) ? 'Edge' : /OPR\/|Opera/.test(s) ? 'Opera' : /Firefox\//.test(s) ? 'Firefox'
|
||||
: /SamsungBrowser\//.test(s) ? 'Samsung Internet' : /Chrome\//.test(s) ? 'Chrome' : /Safari\//.test(s) ? 'Safari' : null;
|
||||
const os = /iPhone|iPad|iPod/.test(s) ? 'iPhone or iPad' : /Android/.test(s) ? 'Android' : /Windows/.test(s) ? 'Windows'
|
||||
: /Mac OS X|Macintosh/.test(s) ? 'a Mac' : /CrOS/.test(s) ? 'a Chromebook' : /Linux/.test(s) ? 'Linux' : null;
|
||||
if (browser && os) return `${browser} on ${os}`;
|
||||
return browser || os || s.slice(0, 120);
|
||||
}
|
||||
|
||||
async function roughLocation(ctx: Ctx, ip: string | null): Promise<string> {
|
||||
if (!ip || PRIVATE_IP.test(ip) || !ctx.config.production) return 'Unknown';
|
||||
try {
|
||||
const res = await fetch(`http://ip-api.com/json/${encodeURIComponent(ip.replace(/^::ffff:/, ''))}?fields=status,city,regionName,country`, { signal: AbortSignal.timeout(3000) });
|
||||
const geo = (await res.json()) as { status?: string; city?: string; regionName?: string; country?: string };
|
||||
const parts = geo.status === 'success' ? [geo.city, geo.regionName, geo.country].filter(Boolean) : [];
|
||||
return parts.length ? parts.join(', ') : 'Unknown';
|
||||
} catch {
|
||||
return 'Unknown';
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: string | null; userAgent: string | null; clientId: string | null }): Promise<'sent' | 'off' | 'failed'> {
|
||||
try {
|
||||
if (!(await ctx.settings.bool('signin_notices', true))) return 'off';
|
||||
const a = await ctx.db.account.findUnique({ where: { id: o.accountId } });
|
||||
if (!a || a.status !== 'active') return 'off';
|
||||
const link = o.clientId ? await ctx.db.productLink.findUnique({ where: { installId: o.clientId } }) : null;
|
||||
const site = link ? productName(link.product) : o.clientId === 'accounts-self' ? 'Your account page' : null;
|
||||
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
|
||||
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
|
||||
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
|
||||
if (a.phone && a.phoneVerified && !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';
|
||||
} catch (e) {
|
||||
console.warn('[sign-in notice] not sent:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
/**
|
||||
* Accounts' admin (`/api/v2/admin/…`, docs/ACCOUNTS-1.0-PLAN.md §8): people, sign-in settings,
|
||||
* linked products, the church profile, privacy notices and deletions, email and WhatsApp, the
|
||||
* linked products, the church profile, privacy notices and deletions, email and WhatsApp, backups,
|
||||
* licence and the audit log. Admins only, signed in with 2FA; viewing a person is access-logged.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import type Provider from 'oidc-provider';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError, handle, limit } from '../http.js';
|
||||
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';
|
||||
@@ -16,10 +20,12 @@ import { church, updateProfile } from '../church/profile.js';
|
||||
import { connectTo, disconnectFrom } from '../links/connect.js';
|
||||
import { linkedProducts } from '../links/store.js';
|
||||
import { approveDeletion, cancelDeletion } from '../privacy/deletion.js';
|
||||
import { currentNotice, publish } from '../privacy/notice.js';
|
||||
import { builtInNotice, currentNotice, publish } from '../privacy/notice.js';
|
||||
import { licenceStatus } from '../hub/licence.js';
|
||||
import { connect as connectHub } from '../hub/client.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
|
||||
import { testEmail } from '../lib/emails.js';
|
||||
|
||||
const PAGE = 50;
|
||||
|
||||
@@ -140,7 +146,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
r.get('/notices', handle(async (req, res) => {
|
||||
await admin(req, res);
|
||||
const list = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'desc' } });
|
||||
return { current: await currentNotice(ctx), items: list };
|
||||
// 1.3.0: the built-in text too, so an admin can start a new version from it.
|
||||
return { current: await currentNotice(ctx), builtIn: await builtInNotice(ctx), items: list };
|
||||
}));
|
||||
|
||||
r.post('/notices', handle(async (req, res) => {
|
||||
@@ -190,13 +197,39 @@ 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 };
|
||||
}));
|
||||
|
||||
r.post('/settings/test-email', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
|
||||
try {
|
||||
await ctx.messenger.email({ to: a.email, ...(await testEmail(ctx)) });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
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);
|
||||
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
|
||||
if (!a.phone) throw new ApiError(400, 'NO_PHONE', 'Add your mobile number on your account page first.');
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: 'WhatsApp from Accounts works.' });
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'NOT_SENT', `The test message couldn't be sent: ${(e as Error).message}`);
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
@@ -228,6 +261,87 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
return disconnectFrom(ctx, String(req.params.installId), me, req);
|
||||
}));
|
||||
|
||||
// ─── Backups (1.3.0) ───────────────────────────────────────────────────────
|
||||
|
||||
r.get('/backups', handle(async (req, res) => {
|
||||
await admin(req, res);
|
||||
const items = await listBackups(ctx);
|
||||
return {
|
||||
items: items.map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })),
|
||||
nightly: await ctx.settings.bool('backup_nightly', true),
|
||||
retain: await retainCount(ctx),
|
||||
lastError: await ctx.settings.get('backup_last_error'),
|
||||
};
|
||||
}));
|
||||
|
||||
r.post('/backups/run', limit(10, 60), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
let b;
|
||||
try {
|
||||
b = await runBackup(ctx);
|
||||
} catch (e) {
|
||||
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`);
|
||||
}
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_made', targetType: 'backup', targetId: b.filename, ip: clientIp(req) });
|
||||
return { filename: b.filename, size: b.size, createdAt: b.createdAt };
|
||||
}));
|
||||
|
||||
r.put('/backups/settings', handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const retain = Number(req.body?.retain);
|
||||
if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' });
|
||||
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: req.body?.nightly === false ? 'false' : 'true' });
|
||||
const deleted = await rotate(ctx);
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly: req.body?.nightly !== false, deleted }, ip: clientIp(req) });
|
||||
return { retain, nightly: req.body?.nightly !== false, deleted };
|
||||
}));
|
||||
|
||||
// A download holds everyone's data: admins only, audited, never cached.
|
||||
r.get('/backups/:file/download', async (req, res) => {
|
||||
try {
|
||||
const me = await admin(req, res);
|
||||
const file = backupPath(ctx, String(req.params.file));
|
||||
if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.');
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file), ip: clientIp(req) });
|
||||
res.setHeader('Content-Type', 'application/gzip');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`);
|
||||
fs.createReadStream(file).pipe(res);
|
||||
} catch (e) {
|
||||
sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Background jobs (1.4.0, as Cross Events) ───────────────────────────────
|
||||
|
||||
const jobError = (e: unknown): never => {
|
||||
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
|
||||
throw e;
|
||||
};
|
||||
|
||||
r.get('/jobs', handle(async (req, res) => {
|
||||
await admin(req, res);
|
||||
return jobStatus(ctx);
|
||||
}));
|
||||
|
||||
// Switch a job on or off, or change its schedule: wins over the .env; null goes back to it.
|
||||
r.put('/jobs/:name', handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const name = String(req.params.name);
|
||||
const change = { enabled: req.body?.enabled, cron: req.body?.cron };
|
||||
const override = await setOverride(ctx, name, change).catch(jobError);
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: change, ip: clientIp(req) });
|
||||
return { name, override };
|
||||
}));
|
||||
|
||||
r.post('/jobs/:name/run', limit(20, 60), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
const name = String(req.params.name);
|
||||
const out = await runNow(ctx, name).catch(jobError);
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_run_manual', targetType: 'job', targetId: name, metadata: { queued: out.queued }, ip: clientIp(req) });
|
||||
return out;
|
||||
}));
|
||||
|
||||
// ─── Licence, audit ────────────────────────────────────────────────────────
|
||||
|
||||
r.get('/licence', handle(async (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,129 @@
|
||||
/**
|
||||
* Database backups (1.3.0, as Cross Events' Settings → Backups): a gzipped `pg_dump` into
|
||||
* backend/backups/ every night at 02:00 and whenever an admin asks, kept on this server only.
|
||||
* The `crosscode` script makes the same files before every deploy and uninstall
|
||||
* (scripts/products/accounts.sh), so the admin's list shows both, newest first.
|
||||
*
|
||||
* Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last
|
||||
* run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client).
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import zlib from 'node:zlib';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */
|
||||
export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups');
|
||||
|
||||
/** The names this module and the crosscode script give a backup: accounts-YYYYMMDD-HHMMSS.sql.gz. */
|
||||
export const BACKUP_FILE = /^accounts-\d{8}-\d{6}\.sql\.gz$/;
|
||||
export const DEFAULT_RETAIN = 14;
|
||||
const MAX_RETAIN = 365;
|
||||
|
||||
export type Backup = { filename: string; size: number; createdAt: Date };
|
||||
|
||||
/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */
|
||||
export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise<void> };
|
||||
|
||||
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
|
||||
|
||||
/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */
|
||||
export const pgDump: Dumper = (databaseUrl) => {
|
||||
const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let stderr = '';
|
||||
child.stderr.on('data', (d) => { stderr += String(d); });
|
||||
const done = new Promise<void>((resolve, reject) => {
|
||||
child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`)));
|
||||
child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`))));
|
||||
});
|
||||
return { stdout: child.stdout, done };
|
||||
};
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
/** accounts-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */
|
||||
export function backupName(at: Date): string {
|
||||
return `accounts-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`;
|
||||
}
|
||||
|
||||
export async function retainCount(ctx: Ctx): Promise<number> {
|
||||
const n = Number(await ctx.settings.get('backup_retain_count'));
|
||||
return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN;
|
||||
}
|
||||
|
||||
/** Every backup in the folder, newest first. */
|
||||
export async function listBackups(ctx: Ctx): Promise<Backup[]> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.promises.readdir(dir(ctx));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => {
|
||||
const st = await fs.promises.stat(path.join(dir(ctx), filename));
|
||||
return { filename, size: st.size, createdAt: st.mtime };
|
||||
}));
|
||||
return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename));
|
||||
}
|
||||
|
||||
/** The newest backup's time, for the Hub heartbeat. */
|
||||
export async function lastBackupAt(ctx: Ctx): Promise<Date | null> {
|
||||
return (await listBackups(ctx))[0]?.createdAt ?? null;
|
||||
}
|
||||
|
||||
/** The full path of a backup to download, or null if there's no such backup (or a bad name). */
|
||||
export function backupPath(ctx: Ctx, filename: string): string | null {
|
||||
if (!BACKUP_FILE.test(filename)) return null;
|
||||
const p = path.join(dir(ctx), filename);
|
||||
return fs.existsSync(p) ? p : null;
|
||||
}
|
||||
|
||||
/** Deletes the oldest backups beyond the number kept. */
|
||||
export async function rotate(ctx: Ctx): Promise<number> {
|
||||
const old = (await listBackups(ctx)).slice(await retainCount(ctx));
|
||||
await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {})));
|
||||
return old.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would
|
||||
* look like a real backup). Records the outcome for the admin page.
|
||||
*/
|
||||
export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise<Backup> {
|
||||
const url = ctx.config.databaseUrl;
|
||||
try {
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
|
||||
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
|
||||
// Two in the same second (the button pressed twice): the next free second's name.
|
||||
const at = ctx.now().getTime();
|
||||
let filename = backupName(new Date(at));
|
||||
for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000));
|
||||
const file = path.join(dir(ctx), filename);
|
||||
const { stdout, done } = dumper(url);
|
||||
// Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way,
|
||||
// so a failed one's file is deleted after the last write, not before it.
|
||||
const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]);
|
||||
const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected');
|
||||
if (failed) {
|
||||
await fs.promises.unlink(file).catch(() => {});
|
||||
throw failed.reason;
|
||||
}
|
||||
await rotate(ctx);
|
||||
await ctx.settings.set('backup_last_error', null);
|
||||
const st = await fs.promises.stat(file);
|
||||
return { filename, size: st.size, createdAt: st.mtime };
|
||||
} catch (e) {
|
||||
await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */
|
||||
export async function runBackupJob(ctx: Ctx) {
|
||||
if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true };
|
||||
const b = await runBackup(ctx);
|
||||
return { filename: b.filename, size: b.size };
|
||||
}
|
||||
@@ -69,10 +69,37 @@ export class ProfileError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
|
||||
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
|
||||
/** The profile changed since the editor loaded it (`church.update` with `ifUpdatedAt`). */
|
||||
export class ProfileChangedError extends Error {
|
||||
constructor(public updatedAt: string) {
|
||||
super('The church profile was changed by someone else since you opened it.');
|
||||
}
|
||||
}
|
||||
|
||||
const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
/**
|
||||
* The fields given replace what's there; `branding` is merged field by field (1.7.0), so a form
|
||||
* that doesn't know `branding.style` (or sends only the style) never drops the rest.
|
||||
*/
|
||||
export function mergeProfile(base: Record<string, unknown>, input: unknown): Record<string, unknown> {
|
||||
if (!isObject(input)) return { ...base };
|
||||
const next: Record<string, unknown> = { ...base, ...input };
|
||||
if (isObject(input.branding)) next.branding = { ...(isObject(base.branding) ? base.branding : {}), ...input.branding };
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves changes (merged onto what's there) from an admin here or a product (`church.update`),
|
||||
* and tells the linked products. With `ifUpdatedAt`, refuses if someone saved since.
|
||||
*/
|
||||
export async function updateProfile(ctx: Ctx, input: unknown, opts: { ifUpdatedAt?: string } = {}): Promise<Church> {
|
||||
const current = await storedProfile(ctx);
|
||||
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
|
||||
if (opts.ifUpdatedAt) {
|
||||
const now = current.updatedAt ?? new Date(0).toISOString();
|
||||
if (new Date(now).getTime() !== new Date(opts.ifUpdatedAt).getTime()) throw new ProfileChangedError(now);
|
||||
}
|
||||
const next = mergeProfile({ ...DEFAULTS(ctx), ...current }, input);
|
||||
const check = profileInputSchema.safeParse(next);
|
||||
if (!check.success) {
|
||||
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
|
||||
@@ -92,6 +119,7 @@ export async function branding(ctx: Ctx) {
|
||||
shortName: c.shortName,
|
||||
logoUrl: c.branding.logoUrl,
|
||||
colours: c.branding.colours,
|
||||
style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: c.branding.style?.corners ?? null },
|
||||
signupEnabled: await ctx.settings.bool('signup_enabled', true),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md §12, "Demo scenarios"): the
|
||||
* scenario's church becomes the church profile (its own name, logo, icon, colours, campuses,
|
||||
* service times and contact details), and its people get accounts. Loaded first, so Cross Events,
|
||||
* the Website and the App then build their demo data around the same church and people.
|
||||
*
|
||||
* Only for demo sites (`crosscode demo <church> accounts --profile <scenario>`, which takes a backup
|
||||
* first). People keep the same account id on every load (`demoId`), so products' copies still match.
|
||||
* Demo people from before who aren't in this scenario are anonymised; real people (any address not at
|
||||
* example.com) and Accounts admins are never touched.
|
||||
*/
|
||||
import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts';
|
||||
import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { hashPassword } from '../lib/passwords.js';
|
||||
import { updateProfile } from '../church/profile.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
|
||||
/** Where Accounts serves the scenario's logo and icon (`/api/demo-assets/<scenario>/logo.svg`). */
|
||||
export const DEMO_ASSETS_PATH = '/api/demo-assets';
|
||||
const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const;
|
||||
|
||||
/** The SVG for a demo asset, or null for anything else. */
|
||||
export function demoAsset(scenario: string, file: string): string | null {
|
||||
const key = agent.demoScenarioSchema.safeParse(scenario);
|
||||
const draw = (DEMO_ASSET_FILES as Record<string, (s: agent.DemoScenarioKey) => string>)[file];
|
||||
return key.success && draw ? draw(key.data) : null;
|
||||
}
|
||||
|
||||
export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number }
|
||||
|
||||
const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
const CHUNK = 500;
|
||||
|
||||
export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise<ScenarioResult> {
|
||||
const { profile } = demoChurch(scenario);
|
||||
const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`;
|
||||
|
||||
// The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed).
|
||||
await updateProfile(ctx, {
|
||||
name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale,
|
||||
branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style },
|
||||
campuses: profile.campuses, serviceTimes: profile.serviceTimes,
|
||||
contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social,
|
||||
});
|
||||
|
||||
// The people.
|
||||
const people = demoPeople(scenario);
|
||||
const wanted = new Set(people.map((p) => p.id));
|
||||
const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a]));
|
||||
let removed = 0;
|
||||
for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) {
|
||||
if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue;
|
||||
await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } });
|
||||
await anonymise(ctx, a.id);
|
||||
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
|
||||
removed++;
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(DEMO_PASSWORD);
|
||||
const notice = await currentNoticeVersion(ctx);
|
||||
const now = ctx.now();
|
||||
const fields = (p: (typeof people)[number]) => ({
|
||||
name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true,
|
||||
phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const,
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now,
|
||||
noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null,
|
||||
whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
});
|
||||
let updated = 0;
|
||||
// Already here (this scenario loaded before, or anonymised when another was): brought back as they were.
|
||||
for (const p of people) {
|
||||
const a = existing.get(p.id);
|
||||
if (!a) continue;
|
||||
// Never take over a real person's account, nor an admin's.
|
||||
if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue;
|
||||
const other = await ctx.db.account.findUnique({ where: { email: p.email } });
|
||||
if (other && other.id !== p.id) continue;
|
||||
await ctx.db.account.update({ where: { id: p.id }, data: fields(p) });
|
||||
updated++;
|
||||
}
|
||||
// New: in chunks, as the larger scenarios have a couple of thousand people.
|
||||
const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email));
|
||||
const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email));
|
||||
for (let i = 0; i < fresh.length; i += CHUNK) {
|
||||
await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) });
|
||||
}
|
||||
|
||||
await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } });
|
||||
await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() }));
|
||||
return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed };
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type { Ctx } from '../context.js';
|
||||
import { hubPublicKey, verifyToken } from './licence.js';
|
||||
import { keyPair, saveLinkedProducts } from '../links/store.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
import { lastBackupAt } from '../backups/backups.js';
|
||||
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
const TIMEOUT_MS = 15000;
|
||||
@@ -55,7 +56,7 @@ export async function health(ctx: Ctx) {
|
||||
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||
db,
|
||||
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
|
||||
lastBackupAt: null,
|
||||
lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null,
|
||||
disk: null,
|
||||
errorsLast24h: null,
|
||||
pendingMigrations: 0,
|
||||
|
||||
@@ -23,8 +23,10 @@ async function main() {
|
||||
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
|
||||
const stopJobs = await startJobs(ctx, url);
|
||||
|
||||
// 1.7.1: a heartbeat on every start, not only the first (as the Website), so the list of the
|
||||
// church's products is fresh after a restart.
|
||||
connectFromEnv(ctx).then((r) => {
|
||||
if (r.connected) heartbeat(ctx).catch(() => {});
|
||||
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
|
||||
}).catch(() => {});
|
||||
|
||||
const stop = async () => {
|
||||
|
||||
@@ -23,6 +23,7 @@ import { loginEvent } from '../lib/audit.js';
|
||||
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
import { applyKnownOptOut } from '../accounts/whatsapp.js';
|
||||
|
||||
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
|
||||
|
||||
@@ -99,19 +100,23 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
|
||||
};
|
||||
if (stage === 'password' || stage === 'done') return base;
|
||||
const a = await account(ctx, pending);
|
||||
let sentNow: string | null = null;
|
||||
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
|
||||
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
|
||||
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
|
||||
sentNow = sent.sentTo;
|
||||
}
|
||||
const extra: Record<string, unknown> = { name: a.name, email: a.email };
|
||||
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
|
||||
if (stage === 'two_factor') {
|
||||
extra.method = a.twoFactorMethod;
|
||||
if (a.twoFactorMethod !== 'totp') extra.sentTo = maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
// Where it actually went (a WhatsApp code that couldn't go was sent by email).
|
||||
if (a.twoFactorMethod !== 'totp') extra.sentTo = sentNow ?? maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
|
||||
}
|
||||
if (stage === 'setup_two_factor') {
|
||||
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
// 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 && !a.whatsappOptedOut ? ['whatsapp'] : [])];
|
||||
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||
}
|
||||
if (stage === 'notice') {
|
||||
@@ -173,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 });
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@ import type Provider from 'oidc-provider';
|
||||
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError, handle, limit } from '../http.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { clientIp, loginEvent } from '../lib/audit.js';
|
||||
import { sendSignInNotice } from '../accounts/signInNotice.js';
|
||||
import { resetPasswordEmail } from '../lib/emails.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { hashPassword, passwordProblem } from '../lib/passwords.js';
|
||||
import { normaliseEmail } from '../accounts/service.js';
|
||||
@@ -43,6 +45,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
const clientId = String(details.params.client_id ?? '') || null;
|
||||
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
|
||||
await signedInThrough(ctx, clientId, pending.accountId);
|
||||
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
|
||||
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
|
||||
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
|
||||
return { stage: 'done', redirectTo, ...extra };
|
||||
}
|
||||
@@ -88,6 +92,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
// ─── Forgot / reset password ───────────────────────────────────────────────
|
||||
|
||||
r.post('/password/forgot', limit(5), handle(async (req) => {
|
||||
// 1.2.0: without email nobody gets a link; say so (the same answer whoever asks).
|
||||
if (!(await ctx.messenger.emailReady())) throw new ApiError(503, 'EMAIL_NOT_READY', 'Password reset links can\'t be sent right now: the church\'s email isn\'t set up. Please let the church office know.');
|
||||
const email = normaliseEmail(req.body?.email);
|
||||
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
|
||||
// The same answer either way, so nobody can find out who has an account (Events 1.51.17).
|
||||
@@ -95,11 +101,7 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
|
||||
const token = randomToken();
|
||||
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
|
||||
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
|
||||
await ctx.messenger.email({
|
||||
to: a.email,
|
||||
subject: 'Reset your password',
|
||||
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
|
||||
});
|
||||
await ctx.messenger.email({ to: a.email, ...(await resetPasswordEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, minutes: RESET_MINUTES })) });
|
||||
}
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
/**
|
||||
* Background jobs on pg-boss (as 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.
|
||||
*
|
||||
* 1.4.0 (as Events 3.4.0): Admin → Background jobs shows each job's schedule and last runs, runs
|
||||
* one now, and switches one on or off or changes its schedule. That choice is kept in the
|
||||
* database (`job_overrides`), wins over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and
|
||||
* JOB_SCHEDULE_<NAME>) and takes effect straight away (in other processes within 30 seconds).
|
||||
*/
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import PgBoss from 'pg-boss';
|
||||
import type { Ctx } from './context.js';
|
||||
import { runBackupJob } from './backups/backups.js';
|
||||
import { heartbeat } from './hub/client.js';
|
||||
import { runDue } from './links/deliveries.js';
|
||||
import { forgetOldRequests } from './links/requests.js';
|
||||
@@ -11,15 +18,17 @@ import { deleteExpired } from './oidc/adapter.js';
|
||||
import { runDeletionJob } from './privacy/deletion.js';
|
||||
import { runExportsJob } from './privacy/export.js';
|
||||
|
||||
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
|
||||
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
|
||||
|
||||
export const JOBS: Job[] = [
|
||||
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
|
||||
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
|
||||
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
|
||||
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
|
||||
{ name: 'deliveries', label: 'Linked products: send what they need to know (sign-outs, changes), retrying failures', cron: '* * * * *', env: null, run: (ctx) => runDue(ctx) },
|
||||
{ name: 'exports', label: 'Privacy: make the copies of their data people asked for', cron: '*/5 * * * *', env: 'EXPORTS_JOB_ENABLED', run: (ctx) => runExportsJob(ctx) },
|
||||
{ name: 'deletions', label: 'Privacy: delete the accounts whose deletion is due', cron: '*/15 * * * *', env: 'DELETIONS_JOB_ENABLED', run: (ctx) => runDeletionJob(ctx) },
|
||||
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
|
||||
{ name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
|
||||
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
|
||||
{
|
||||
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
|
||||
name: 'cleanup', label: 'Delete expired sign-ins, codes and links', cron: '17 * * * *', env: null,
|
||||
run: async (ctx) => {
|
||||
const now = ctx.now();
|
||||
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
|
||||
@@ -34,23 +43,261 @@ export const JOBS: Job[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
|
||||
if (!ctx.config.jobsEnabled) return async () => {};
|
||||
const tz = ctx.config.timezone;
|
||||
const SCHEMA = 'pgboss_accounts';
|
||||
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 {
|
||||
const boss = new PgBoss({ connectionString, schema: 'pgboss_accounts', application_name: 'crosscode-accounts-jobs' });
|
||||
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
|
||||
await boss.start();
|
||||
for (const job of JOBS) {
|
||||
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
|
||||
await boss.schedule(job.name, job.cron, undefined, { tz });
|
||||
await boss.work(job.name, async () => job.run(ctx));
|
||||
}
|
||||
console.log(`[jobs] Job queue started: ${JOBS.map((j) => j.name).join(', ')}.`);
|
||||
return async () => { await boss.stop({ graceful: true }); };
|
||||
} catch (e) {
|
||||
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
|
||||
const timers = JOBS.map((job) => setInterval(() => { job.run(ctx).catch((err) => console.warn(`[jobs] ${job.name}:`, (err as Error).message)); }, job.everyMs));
|
||||
return async () => { timers.forEach(clearInterval); };
|
||||
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-accounts-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) ?? [],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -20,9 +20,15 @@ export type Config = {
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
|
||||
/** 1.2.0: WAWP from the .env when the database has none (as Cross Events). */
|
||||
wawp: { accessToken: string; instanceId: string } | null;
|
||||
/** Local testing only: linked products on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
jobsEnabled: boolean;
|
||||
/** 1.3.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */
|
||||
databaseUrl: string | null;
|
||||
/** 1.3.0: where backups go; default backend/backups (tests use their own folder). */
|
||||
backupDir: string | null;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
@@ -67,7 +73,10 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
|
||||
smtp: env.SMTP_HOST
|
||||
? { host: env.SMTP_HOST, port: Number(env.SMTP_PORT || 587), user: env.SMTP_USER || '', pass: env.SMTP_PASS || '', from: env.SMTP_FROM || env.SMTP_USER || '', secure: bool(env.SMTP_SECURE, Number(env.SMTP_PORT) === 465) }
|
||||
: null,
|
||||
wawp: env.WAWP_ACCESS_TOKEN && env.WAWP_INSTANCE_ID ? { accessToken: env.WAWP_ACCESS_TOKEN, instanceId: env.WAWP_INSTANCE_ID } : null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
databaseUrl: env.DATABASE_URL?.trim() || null,
|
||||
backupDir: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* The emails Accounts sends (1.4.0), styled as Cross Events' (apps/events/backend/src/utils/email.js):
|
||||
* a header in the church's colour with its logo or name, a white card, a button for the one thing
|
||||
* to do with the link written out under it, and a footer with the church's contact details.
|
||||
*
|
||||
* Every email also has the plain text it always had (some mail apps show only that, and the tests
|
||||
* read codes and links from it). Everything put into the HTML is escaped; colours and links are
|
||||
* checked first.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { church } from '../church/profile.js';
|
||||
|
||||
export type Built = { subject: string; text: string; html: string };
|
||||
|
||||
type Brand = { name: string; colour: string; accent: string; logoUrl: string | null; email: string | null; phone: string | null; url: string };
|
||||
|
||||
const FONT = `-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif`;
|
||||
const MONO = `'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace`;
|
||||
const HEX = /^#[0-9a-fA-F]{6}$/;
|
||||
|
||||
export const esc = (s: unknown) => String(s ?? '')
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||||
|
||||
/** Only http(s) links go in an href. */
|
||||
const safeUrl = (u: string) => (/^https?:\/\//i.test(u) ? u : '#');
|
||||
|
||||
/** A darker shade of a #rrggbb colour, for the header's gradient. */
|
||||
function darker(hex: string, by = 0.25): string {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
const ch = (shift: number) => Math.max(0, Math.round(((n >> shift) & 255) * (1 - by)));
|
||||
return `#${[ch(16), ch(8), ch(0)].map((c) => c.toString(16).padStart(2, '0')).join('')}`;
|
||||
}
|
||||
|
||||
async function brand(ctx: Ctx): Promise<Brand> {
|
||||
const base = ctx.config.publicUrl.replace(/\/+$/, '');
|
||||
try {
|
||||
const c = await church(ctx);
|
||||
const logo = c.branding.logoUrl;
|
||||
return {
|
||||
name: c.name || 'Your church',
|
||||
colour: HEX.test(c.branding.colours.primary) ? c.branding.colours.primary : '#1f4e79',
|
||||
accent: c.branding.colours.accent && HEX.test(c.branding.colours.accent) ? c.branding.colours.accent : '#f2a900',
|
||||
logoUrl: logo ? (logo.startsWith('/') ? `${base}${logo}` : /^https:\/\//i.test(logo) ? logo : null) : null,
|
||||
email: c.contact.email ?? null,
|
||||
phone: c.contact.phone ?? null,
|
||||
url: base,
|
||||
};
|
||||
} catch {
|
||||
return { name: 'Your church', colour: '#1f4e79', accent: '#f2a900', logoUrl: null, email: null, phone: null, url: base };
|
||||
}
|
||||
}
|
||||
|
||||
/** The page around an email's body (Cross Events' layout). */
|
||||
function layout(b: Brand, body: string, preheader: string): string {
|
||||
const header = b.logoUrl
|
||||
? `<img src="${esc(b.logoUrl)}" alt="${esc(b.name)}" height="56" style="display:block;margin:0 auto;max-height:56px;max-width:240px;border:0">`
|
||||
: `<h1 style="color:#ffffff;font-size:26px;font-weight:800;margin:0;letter-spacing:-0.5px;font-family:${FONT};text-shadow:0 1px 3px rgba(0,0,0,0.3)">${esc(b.name)}</h1>`;
|
||||
const contact = [
|
||||
esc(b.name),
|
||||
b.email ? `<a href="mailto:${esc(b.email)}" style="color:#94a3b8;text-decoration:underline">${esc(b.email)}</a>` : '',
|
||||
b.phone ? esc(b.phone) : '',
|
||||
].filter(Boolean).join(' • ');
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
|
||||
<title>${esc(b.name)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background-color:#f1f5f9;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%">
|
||||
<div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all">${esc(preheader)}‌ ‌ ‌ </div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f1f5f9">
|
||||
<tr><td align="center" style="padding:40px 16px">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px">
|
||||
<tr><td style="background:${b.colour};background:linear-gradient(135deg,${b.colour} 0%,${darker(b.colour)} 100%);border-radius:12px 12px 0 0;padding:36px 48px;text-align:center">
|
||||
${header}
|
||||
<p style="color:#ffffff;font-size:13px;font-weight:500;margin:10px 0 0 0;font-family:${FONT};letter-spacing:0.3px;opacity:0.9">Your ${esc(b.name)} account</p>
|
||||
</td></tr>
|
||||
<tr><td style="background:#ffffff;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;padding:44px 48px 36px 48px">
|
||||
<div style="font-family:${FONT};color:#1e293b;font-size:15px;line-height:1.75">
|
||||
${body}
|
||||
</div>
|
||||
</td></tr>
|
||||
<tr><td style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;padding:24px 48px;text-align:center">
|
||||
<p style="color:#94a3b8;font-size:12px;margin:0 0 4px 0;font-family:${FONT}">${contact}</p>
|
||||
<p style="color:#cbd5e1;font-size:11px;margin:6px 0 0 0;font-family:${FONT}">You're getting this because you have an account with ${esc(b.name)}, used to sign in to its sites.</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
const title = (t: string, sub?: string) =>
|
||||
`<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0;letter-spacing:-0.3px">${esc(t)}</p>` +
|
||||
(sub ? `<p style="color:#64748b;font-size:14px;margin:0 0 28px 0">${esc(sub)}</p>` : '');
|
||||
const hello = (name?: string | null) => `<p style="margin:0 0 8px 0;color:#374151">Hello <strong>${esc(name || 'there')}</strong>,</p>`;
|
||||
const para = (html: string) => `<p style="margin:0 0 20px 0;color:#374151">${html}</p>`;
|
||||
const divider = () => `<div style="border-top:1px solid #f1f5f9;margin:28px 0"></div>`;
|
||||
const small = (html: string) => `<p style="margin:0;font-size:13px;color:#94a3b8">${html}</p>`;
|
||||
|
||||
function button(b: Brand, label: string, url: string): string {
|
||||
const href = esc(safeUrl(url));
|
||||
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:28px auto 8px auto">
|
||||
<tr><td align="center" style="border-radius:8px;background-color:${b.colour}">
|
||||
<a href="${href}" target="_blank" style="display:inline-block;padding:14px 36px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;font-family:${FONT};letter-spacing:0.2px">${esc(label)}</a>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="text-align:center;margin:4px 0 0 0;font-size:12px;color:#94a3b8;word-break:break-all">Or copy this link: <a href="${href}" style="color:${b.colour}">${esc(url)}</a></p>`;
|
||||
}
|
||||
|
||||
/** Info, a warning ("if this wasn't you") or neutral: these colours never follow the church's. */
|
||||
function callout(html: string, kind: 'info' | 'warning' | 'success' = 'info'): string {
|
||||
const s = { info: ['#eff6ff', '#3b82f6', '#1e40af'], warning: ['#fffbeb', '#f59e0b', '#92400e'], success: ['#f0fdf4', '#22c55e', '#166534'] }[kind];
|
||||
return `<div style="background:${s[0]};border-left:4px solid ${s[1]};border-radius:0 6px 6px 0;padding:14px 18px;margin:24px 0;color:${s[2]};font-size:14px;line-height:1.6">${html}</div>`;
|
||||
}
|
||||
|
||||
const code6 = (code: string) =>
|
||||
`<p style="margin:8px 0 24px 0;font-size:34px;font-weight:800;letter-spacing:8px;color:#0f172a;text-align:center;font-family:${MONO}">${esc(code)}</p>`;
|
||||
|
||||
const contactLine = (b: Brand) => (b.email ? ` at <a href="mailto:${esc(b.email)}" style="color:${b.colour}">${esc(b.email)}</a>` : '');
|
||||
|
||||
// ─── The emails ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** A sign-in or confirm-your-email code (the text is the WhatsApp message too). */
|
||||
export async function codeEmail(ctx: Ctx, o: { name?: string | null; code: string; text: string; purpose: 'sign_in' | 'verify_email' | 'setup'; minutes: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const what = o.purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
|
||||
const body = title('Your code', o.purpose === 'verify_email' ? 'To confirm your email address' : `To sign in to ${b.name}`)
|
||||
+ hello(o.name)
|
||||
+ para(`Enter this code to ${esc(what)}. It works for <strong>${o.minutes} minutes</strong>.`)
|
||||
+ code6(o.code)
|
||||
+ divider()
|
||||
+ small(`Never share this code with anyone, not even someone from the church. If you didn't ask for it, you can ignore this email: nobody can sign in without your password${o.purpose === 'sign_in' ? ' and this code' : ''}.`);
|
||||
return { subject: `Your code: ${o.code}`, text: o.text, html: layout(b, body, `Your code is ${o.code}. It works for ${o.minutes} minutes.`) };
|
||||
}
|
||||
|
||||
export async function resetPasswordEmail(ctx: Ctx, o: { name?: string | null; url: string; minutes: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Reset your password', 'Someone (we hope you) asked to reset it.')
|
||||
+ hello(o.name)
|
||||
+ para(`Choose a new password with the button below. The link works for <strong>${o.minutes} minutes</strong>, once.`)
|
||||
+ button(b, 'Choose a new password', o.url)
|
||||
+ divider()
|
||||
+ small(`If you didn't ask, you can ignore this email: your password stays the same. Worried? Let the church office know${contactLine(b)}.`);
|
||||
const text = `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${o.minutes} minutes):\n${o.url}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`;
|
||||
return { subject: 'Reset your password', text, html: layout(b, body, `Choose a new password. The link works for ${o.minutes} minutes.`) };
|
||||
}
|
||||
|
||||
/** A product (Cross Events) made someone an account: choose a password. */
|
||||
export async function newAccountEmail(ctx: Ctx, o: { name: string; url: string; days: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title(`Welcome to ${b.name}`, 'An account has been made for you.')
|
||||
+ hello(o.name)
|
||||
+ para(`${esc(b.name)} has made you an account. It signs you in to all of the church's sites, such as events and registrations. Choose your password to start using it.`)
|
||||
+ button(b, 'Choose my password', o.url)
|
||||
+ callout(`The link works for <strong>${o.days} days</strong>. After that, use <em>Forgot your password?</em> on the sign-in page.`, 'info')
|
||||
+ small('If you weren\'t expecting this, you can ignore this email.');
|
||||
const text = `Hello ${o.name},\n\n${b.name} has made you an account. Choose your password here (the link works for ${o.days} days):\n${o.url}\n\nIf you weren't expecting this, you can ignore this email.`;
|
||||
return { subject: `Your account at ${b.name}`, text, html: layout(b, body, `Choose your password for your ${b.name} account.`) };
|
||||
}
|
||||
|
||||
export async function confirmNewEmail(ctx: Ctx, o: { name?: string | null; url: string }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Confirm your new email address')
|
||||
+ hello(o.name)
|
||||
+ para('You asked to sign in with this email address from now on. Confirm it\'s yours with the button below; until then you keep signing in with your old one.')
|
||||
+ button(b, 'Confirm this address', o.url)
|
||||
+ divider()
|
||||
+ small('The link works for 24 hours. If you didn\'t ask for this, you can ignore this email.');
|
||||
const text = `Confirm this is your new email address for signing in:\n${o.url}\n\nThe link works for 24 hours.`;
|
||||
return { subject: 'Confirm your new email address', text, html: layout(b, body, 'Confirm your new sign-in email address.') };
|
||||
}
|
||||
|
||||
export async function emailChangedNotice(ctx: Ctx, o: { name?: string | null; newEmail: string }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Your sign-in email address changed')
|
||||
+ hello(o.name)
|
||||
+ para(`Your account now signs in with <strong>${esc(o.newEmail)}</strong>. Emails about your account go there from now on.`)
|
||||
+ callout(`<strong>Wasn't you?</strong> Contact the church office straight away${contactLine(b)}.`, 'warning');
|
||||
const text = `Your account now signs in with ${o.newEmail}. If you didn't do this, contact the church office straight away.`;
|
||||
return { subject: 'Your sign-in email address changed', text, html: layout(b, body, `Your account now signs in with ${o.newEmail}.`) };
|
||||
}
|
||||
|
||||
export async function exportReadyEmail(ctx: Ctx, o: { name?: string | null; url: string; days: number }): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Your data is ready', 'The copy you asked for')
|
||||
+ hello(o.name)
|
||||
+ para('The copy of your data you asked for is ready. Download it from your account page.')
|
||||
+ button(b, 'Download my data', o.url)
|
||||
+ callout(`It's kept for <strong>${o.days} days</strong>, then deleted. You need to be signed in to download it.`, 'info');
|
||||
const text = `The copy of your data you asked for is ready. Download it from your account page (it's kept for ${o.days} days):\n${o.url}`;
|
||||
return { subject: 'Your data is ready to download', text, html: layout(b, body, 'The copy of your data you asked for is ready.') };
|
||||
}
|
||||
|
||||
/** A test from the admin page or from a linked product (`from`: "Cross Events"). */
|
||||
export async function testEmail(ctx: Ctx, o: { from?: string } = {}): Promise<Built> {
|
||||
const b = await brand(ctx);
|
||||
const body = title('Email works', o.from ? `A test sent from ${o.from}` : 'A test from Accounts')
|
||||
+ para(`This is a test from ${esc(b.name)}'s sign-in (Accounts)${o.from ? `, sent from ${esc(o.from)}` : ''}.`)
|
||||
+ callout('Email is set up: sign-in codes, password links and security notices can be sent.', 'success');
|
||||
const text = o.from
|
||||
? `This is a test from ${b.name}'s sign-in (Accounts), sent from ${o.from}. Email works: sign-in codes and password links can be sent.`
|
||||
: 'Email from Accounts works.';
|
||||
return { subject: o.from ? `Test email from ${b.name}'s sign-in` : 'Test email from Accounts', text, html: layout(b, body, 'A test email: email works.') };
|
||||
}
|
||||
|
||||
/** A sign-in happened (1.6.0, as Cross Events' "New login detected"). `whatsapp`: the same in a few lines. */
|
||||
export async function newSignInEmail(ctx: Ctx, o: { name?: string | null; when: string; location: string; device: string; site: string | null }): Promise<Built & { whatsapp: string }> {
|
||||
const b = await brand(ctx);
|
||||
const row = (k: string, v: string) => `<tr><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#64748b;font-size:13px;font-weight:600;width:34%">${esc(k)}</td><td style="padding:10px 14px;border-top:1px solid #f1f5f9;color:#1e293b;font-size:14px;word-break:break-word">${esc(v)}</td></tr>`;
|
||||
const body = title('New sign-in', `Someone signed in to your ${b.name} account`)
|
||||
+ hello(o.name)
|
||||
+ `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin:0 0 8px 0">`
|
||||
+ row('When', o.when) + (o.site ? row('Signed in to', o.site) : '') + row('Where (roughly)', o.location) + row('Device', o.device)
|
||||
+ '</table>'
|
||||
+ callout(`<strong>Not you?</strong> Change your password straight away from your account page, and let the church office know${contactLine(b)}.`, 'warning')
|
||||
+ small('If this was you, there\'s nothing to do.');
|
||||
const lines = [`When: ${o.when}`, ...(o.site ? [`Signed in to: ${o.site}`] : []), `Where (roughly): ${o.location}`, `Device: ${o.device}`];
|
||||
const text = `Hello ${o.name || 'there'},\n\nSomeone signed in to your ${b.name} account.\n\n${lines.join('\n')}\n\nIf this wasn't you, change your password straight away and let the church office know${b.email ? ` (${b.email})` : ''}.\nIf it was you, there's nothing to do.`;
|
||||
const whatsapp = `🔐 *New sign-in*\n\nHello ${o.name || 'there'}, someone signed in to your *${b.name}* account.\n\n${lines.join('\n')}\n\nNot you? Change your password straight away and let the church office know.`;
|
||||
return { subject: `New sign-in to your ${b.name} account`, text, html: layout(b, body, `New sign-in: ${o.when}, ${o.device}.`), whatsapp };
|
||||
}
|
||||
@@ -5,14 +5,53 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export type Email = { to: string; subject: string; text: string };
|
||||
/** `html` (1.4.0, src/lib/emails.ts): the styled version; `text` is always sent too. */
|
||||
export type Email = { to: string; subject: string; text: string; html?: string };
|
||||
export type WhatsApp = { to: string; text: string };
|
||||
|
||||
/** SMTP settings to try before saving them (1.2.0), as kept in `smtp_*`. */
|
||||
export type SmtpTry = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
|
||||
/** WAWP settings to try before saving them (1.2.0). */
|
||||
export type WawpTry = { accessToken: string; instanceId: string };
|
||||
|
||||
export interface Messenger {
|
||||
email(msg: Email): Promise<void>;
|
||||
whatsapp(msg: WhatsApp): Promise<void>;
|
||||
/** Whether email is set up (sign-in codes, password links and new accounts need it). */
|
||||
emailReady(): Promise<boolean>;
|
||||
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
|
||||
whatsappReady(): Promise<boolean>;
|
||||
/** Sends one email with settings that aren't saved (a test before saving them). Throws why it failed. */
|
||||
emailWith(settings: SmtpTry, msg: Email): Promise<void>;
|
||||
/** Sends one WhatsApp message with settings that aren't saved. Throws why it failed. */
|
||||
whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void>;
|
||||
}
|
||||
|
||||
/** Thrown when a message can't be sent: the sign-in pages show it instead of failing. */
|
||||
export class SendError extends Error {
|
||||
status = 503;
|
||||
constructor(message: string, public code = 'NOT_SENT') {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function transportFor(s: SmtpTry) {
|
||||
return nodemailer.createTransport({
|
||||
host: s.host, port: s.port, secure: s.secure, auth: s.user ? { user: s.user, pass: s.pass } : undefined,
|
||||
connectionTimeout: 15000, greetingTimeout: 15000, socketTimeout: 20000,
|
||||
});
|
||||
}
|
||||
|
||||
async function wawpSend(s: WawpTry, msg: WhatsApp) {
|
||||
const number = waNumber(msg.to);
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: s.accessToken, instance_id: s.instanceId, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
}
|
||||
|
||||
/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */
|
||||
@@ -49,26 +88,36 @@ export class LiveMessenger implements Messenger {
|
||||
return;
|
||||
}
|
||||
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text });
|
||||
await smtp.transport.sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${smtp.from}>` : smtp.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
|
||||
}
|
||||
|
||||
async emailReady(): Promise<boolean> {
|
||||
return !!(await this.smtp());
|
||||
}
|
||||
|
||||
private async wawp(): Promise<WawpTry | null> {
|
||||
const accessToken = (await this.ctx.settings.get('wawp_access_token')) || this.ctx.config.wawp?.accessToken;
|
||||
const instanceId = (await this.ctx.settings.get('wawp_instance_id')) || this.ctx.config.wawp?.instanceId;
|
||||
return accessToken && instanceId ? { accessToken, instanceId } : null;
|
||||
}
|
||||
|
||||
async whatsappReady(): Promise<boolean> {
|
||||
return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id')));
|
||||
return !!(await this.wawp());
|
||||
}
|
||||
|
||||
async whatsapp(msg: WhatsApp): Promise<void> {
|
||||
const token = await this.ctx.settings.get('wawp_access_token');
|
||||
const instance = await this.ctx.settings.get('wawp_instance_id');
|
||||
const number = waNumber(msg.to);
|
||||
if (!token || !instance) throw new Error('WhatsApp isn\'t set up.');
|
||||
if (!number) throw new Error('That isn\'t a WhatsApp number.');
|
||||
const res = await fetch('https://api.wawp.net/v2/send/text', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ access_token: token, instance_id: instance, chatId: `${number}@c.us`, message: msg.text }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`WhatsApp couldn't send the message (${res.status}).`);
|
||||
const s = await this.wawp();
|
||||
if (!s) throw new Error('WhatsApp isn\'t set up.');
|
||||
await wawpSend(s, msg);
|
||||
}
|
||||
|
||||
async emailWith(settings: SmtpTry, msg: Email): Promise<void> {
|
||||
const church = (await this.ctx.settings.json<{ name?: string }>('church_profile', {})).name;
|
||||
await transportFor(settings).sendMail({ from: church ? `"${church.replace(/"/g, '')}" <${settings.from}>` : settings.from, to: msg.to, subject: msg.subject, text: msg.text, ...(msg.html ? { html: msg.html } : {}) });
|
||||
}
|
||||
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp): Promise<void> {
|
||||
await wawpSend(settings, msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,9 +125,30 @@ export class MemoryMessenger implements Messenger {
|
||||
emails: Email[] = [];
|
||||
whatsapps: WhatsApp[] = [];
|
||||
whatsappOn = false;
|
||||
async email(msg: Email) { this.emails.push(msg); }
|
||||
async whatsapp(msg: WhatsApp) { this.whatsapps.push(msg); }
|
||||
/** Tests: false makes email fail as an unset SMTP does in production. */
|
||||
emailOn = true;
|
||||
/** Tests: settings tried with emailWith / whatsappWith, and a host that fails. */
|
||||
tried: { kind: 'email' | 'whatsapp'; settings: SmtpTry | WawpTry; to: string }[] = [];
|
||||
failHost: string | null = null;
|
||||
async email(msg: Email) {
|
||||
if (!this.emailOn) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).');
|
||||
this.emails.push(msg);
|
||||
}
|
||||
async whatsapp(msg: WhatsApp) {
|
||||
if (!this.whatsappOn) throw new Error('WhatsApp isn\'t set up.');
|
||||
this.whatsapps.push(msg);
|
||||
}
|
||||
async emailReady() { return this.emailOn; }
|
||||
async whatsappReady() { return this.whatsappOn; }
|
||||
async emailWith(settings: SmtpTry, msg: Email) {
|
||||
this.tried.push({ kind: 'email', settings, to: msg.to });
|
||||
if (settings.host === this.failHost) throw new Error(`connect ECONNREFUSED ${settings.host}:${settings.port}`);
|
||||
this.emails.push(msg);
|
||||
}
|
||||
async whatsappWith(settings: WawpTry, msg: WhatsApp) {
|
||||
this.tried.push({ kind: 'whatsapp', settings, to: msg.to });
|
||||
this.whatsapps.push(msg);
|
||||
}
|
||||
/** The last 6-digit code sent to `to` (tests). */
|
||||
lastCode(to: string): string | null {
|
||||
const all = [...this.emails.filter((e) => e.to === to).map((e) => e.text), ...this.whatsapps.filter((w) => w.to === to).map((w) => w.text)];
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
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([
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
|
||||
'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'signin_notices',
|
||||
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
|
||||
'wawp_access_token', 'wawp_instance_id',
|
||||
]);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { heartbeat } from '../hub/client.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { callSibling, LinkCallError, siblingUrl } from './http.js';
|
||||
import { keyPair, listedProduct } from './store.js';
|
||||
@@ -24,6 +25,29 @@ export class LinkError extends Error {
|
||||
/** Products that sign people in through Accounts. */
|
||||
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
|
||||
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||
const REFRESH_EVERY_MS = 60 * 1000;
|
||||
|
||||
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
|
||||
|
||||
/**
|
||||
* 1.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
|
||||
* after Accounts' last heartbeat), Accounts asks the Hub for a fresh list with a heartbeat and looks
|
||||
* again, so a new Website links straight away instead of up to 30 minutes later. There's at most
|
||||
* one such heartbeat a minute, so a message from an unknown install can't make Accounts call the Hub
|
||||
* more often than that.
|
||||
*/
|
||||
async function listedOrRefreshed(ctx: Ctx, installId: string) {
|
||||
const found = await listedProduct(ctx, installId);
|
||||
if (found) return found;
|
||||
const now = ctx.now().getTime();
|
||||
let r = refreshes.get(ctx);
|
||||
if (!r || now - r.at >= REFRESH_EVERY_MS) {
|
||||
r = { at: now, run: heartbeat(ctx).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
|
||||
refreshes.set(ctx, r);
|
||||
}
|
||||
await r.run;
|
||||
return listedProduct(ctx, installId);
|
||||
}
|
||||
|
||||
async function self(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
@@ -55,8 +79,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
|
||||
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
|
||||
|
||||
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
|
||||
const sibling = await listedProduct(ctx, installId);
|
||||
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||
const sibling = await listedOrRefreshed(ctx, installId);
|
||||
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
|
||||
const me = await self(ctx);
|
||||
const secret = newLinkSecret();
|
||||
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||
@@ -86,9 +110,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const sibling = await listedProduct(ctx, m.from.installId);
|
||||
const sibling = await listedOrRefreshed(ctx, m.from.installId);
|
||||
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
|
||||
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
|
||||
throw new LinkError('The Hub doesn\'t list that install for this church (Accounts asks it again at most once a minute).', 'NOT_LINKED', 403);
|
||||
}
|
||||
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
|
||||
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, `church.changed` and (1.9.0) `messaging.changed`. Each is a
|
||||
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
|
||||
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
|
||||
* export).
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS, MESSAGING_CHANGED_PATH } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { callSibling, siblingUrl } from './http.js';
|
||||
@@ -14,7 +14,10 @@ import { callSibling, siblingUrl } from './http.js';
|
||||
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
|
||||
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
|
||||
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed' | 'messaging.changed';
|
||||
|
||||
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
|
||||
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
|
||||
|
||||
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
|
||||
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
|
||||
@@ -23,7 +26,7 @@ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: str
|
||||
for (const link of links) {
|
||||
const callId = crypto.randomUUID();
|
||||
made.push(await ctx.db.delivery.create({
|
||||
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
data: { linkId: link.installId, callId, type, path: PATHS[type] ?? ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
}));
|
||||
}
|
||||
return made;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 4): one set of email and WhatsApp settings per church,
|
||||
* kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the
|
||||
* Church App) are sent `messaging.changed` when they change, so they fetch them again.
|
||||
*/
|
||||
import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { queueCall } from './deliveries.js';
|
||||
|
||||
/** The settings that make up the church's email and WhatsApp. */
|
||||
const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']);
|
||||
const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']);
|
||||
|
||||
/** Which parts the changed setting keys touch. */
|
||||
export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } {
|
||||
return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the change and tells every product that asked for the settings, except the one that
|
||||
* made the change (`exceptLinkId`, e.g. Events saving its own into Accounts).
|
||||
*/
|
||||
export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) {
|
||||
if (!parts.email && !parts.whatsapp) return;
|
||||
const at = ctx.now().toISOString();
|
||||
await ctx.settings.set('messaging_updated_at', at);
|
||||
const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } });
|
||||
const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId);
|
||||
if (!linkIds.length) return;
|
||||
await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds });
|
||||
}
|
||||
@@ -15,20 +15,31 @@ import crypto from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import type Provider from 'oidc-provider';
|
||||
import {
|
||||
ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
|
||||
type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
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';
|
||||
import { audit, clientIp, loginEvent } from '../lib/audit.js';
|
||||
import { newAccountEmail, testEmail } from '../lib/emails.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
import { BUILT_IN_VERSION } from '../privacy/notice.js';
|
||||
import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js';
|
||||
import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent } from '../accounts/service.js';
|
||||
import { turnOff } from '../accounts/twoFactor.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
|
||||
import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js';
|
||||
import { messagingChanged } from './messaging.js';
|
||||
|
||||
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
|
||||
const PROFILE_EDITORS = new Set(['website']);
|
||||
|
||||
/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */
|
||||
export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
|
||||
export class RequestError extends Error {
|
||||
constructor(message: string, public code: string, public status = 400) {
|
||||
@@ -125,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 };
|
||||
}
|
||||
@@ -166,13 +178,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await ctx.db.privacyNotice.create({ data: { version: n.version, title: n.title, body: n.body, publishedAt: new Date(n.publishedAt), publishedById: null } });
|
||||
}
|
||||
}
|
||||
const stored = await ctx.settings.json<Record<string, unknown> & { branding?: { colours?: { primary?: string; accent?: string } } }>('church_profile', {});
|
||||
const next = { ...stored };
|
||||
if (!stored.name && r.church.name) next.name = r.church.name;
|
||||
if (!stored.branding?.colours?.primary && r.church.primaryColour) {
|
||||
next.branding = { logoUrl: null, iconUrl: null, ...(stored.branding ?? {}), colours: { accent: '#f2a900', ...(stored.branding?.colours ?? {}), primary: r.church.primaryColour } } as never;
|
||||
}
|
||||
if (JSON.stringify(next) !== JSON.stringify(stored)) await ctx.settings.set('church_profile', JSON.stringify(next));
|
||||
await applyLook(ctx, r.church, false);
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: ctx.now() } });
|
||||
await logRequest(ctx, link, r, 'import_started', null, req, { notices: noticesTaken ? r.notices.length : 0 });
|
||||
}
|
||||
@@ -222,19 +228,23 @@ 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;
|
||||
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), returnUrl, expiresAt: new Date(ctx.now().getTime() + SET_PASSWORD_DAYS * 86400e3) } });
|
||||
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
await ctx.messenger.email({
|
||||
to: email,
|
||||
subject: `Your account at ${churchName}`,
|
||||
text: `Hello ${r.name},\n\n${churchName} has made you an account. Choose your password here (the link works for ${SET_PASSWORD_DAYS} days):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you weren't expecting this, you can ignore this email.`,
|
||||
});
|
||||
// 1.2.0: the account stands even when the email can't go (they can use "Forgot your password?"
|
||||
// once email works); the product is told.
|
||||
let emailSent = true;
|
||||
try {
|
||||
await ctx.messenger.email({ to: email, ...(await newAccountEmail(ctx, { name: r.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, days: SET_PASSWORD_DAYS })) });
|
||||
} catch (e) {
|
||||
emailSent = false;
|
||||
console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message);
|
||||
}
|
||||
await loginEvent(ctx, a.id, 'account_created', req, { clientId: link.installId, detail: { by: 'product', product: link.product } });
|
||||
await logRequest(ctx, link, r, 'person_created_by_product', a.id, req);
|
||||
return reply({ sub: a.id, created: true });
|
||||
await logRequest(ctx, link, r, 'person_created_by_product', a.id, req, { emailSent });
|
||||
return reply({ sub: a.id, created: true, emailSent });
|
||||
}
|
||||
case 'people.update': {
|
||||
const a = await knownAccount(ctx, link, r.sub);
|
||||
@@ -253,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 });
|
||||
@@ -282,6 +292,119 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req);
|
||||
return reply({ ok: true as const });
|
||||
}
|
||||
case 'people.removeDemo': {
|
||||
// 1.3.0: a product's new demo data replaces the old; the old demo people's accounts go.
|
||||
const kept: { sub: string; reason: 'not_demo' | 'admin' | 'unknown' }[] = [];
|
||||
let removed = 0;
|
||||
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: r.subs } }, select: { accountId: true } })).map((p) => p.accountId));
|
||||
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: [...known] } } })).map((a) => [a.id, a]));
|
||||
for (const sub of new Set(r.subs)) {
|
||||
const a = accounts.get(sub);
|
||||
if (!a || a.status === 'deleted') { kept.push({ sub, reason: 'unknown' }); continue; }
|
||||
if (!isDemoEmail(a.email)) { kept.push({ sub, reason: 'not_demo' }); continue; }
|
||||
if (a.role === 'admin') { kept.push({ sub, reason: 'admin' }); continue; }
|
||||
await signOutEverywhere(ctx, provider, a.id);
|
||||
await anonymise(ctx, a.id);
|
||||
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
|
||||
removed++;
|
||||
}
|
||||
await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length });
|
||||
return reply({ removed, kept });
|
||||
}
|
||||
case 'people.check': {
|
||||
// 1.5.0: the product's regular check that its copies are current. Profiles only for people
|
||||
// this product knows; a deleted account is said to be deleted (its sub was that person's).
|
||||
const subs = [...new Set(r.subs)];
|
||||
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: subs } }, select: { accountId: true } })).map((p) => p.accountId));
|
||||
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: subs } } })).map((a) => [a.id, a]));
|
||||
const people = subs.map((sub) => {
|
||||
const a = accounts.get(sub);
|
||||
if (a?.status === 'deleted') return { sub, status: 'deleted' as const, profile: null };
|
||||
if (!a || !known.has(sub)) return { sub, status: 'unknown' as const, profile: null };
|
||||
return { sub, status: a.status === 'deactivated' ? 'deactivated' as const : 'active' as const, profile: profileOf(a) };
|
||||
});
|
||||
const count = (s: string) => people.filter((p) => p.status === s).length;
|
||||
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
|
||||
return reply({ people });
|
||||
}
|
||||
case 'messaging.get': {
|
||||
// 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings,
|
||||
// secrets sealed with the link's secret. The product is sent messaging.changed from now on.
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } });
|
||||
const out = await messagingSettings(ctx, secret);
|
||||
await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp });
|
||||
return reply(out);
|
||||
}
|
||||
case 'whatsapp.optout': {
|
||||
// 1.9.0 (decision 11): a STOP the product received. Kept here for every product.
|
||||
const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) });
|
||||
await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts });
|
||||
return reply({ accounts });
|
||||
}
|
||||
case 'church.update': {
|
||||
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
|
||||
// checks it's the Website, that the person signs in through it, and audits it as theirs.
|
||||
if (!PROFILE_EDITORS.has(link.product)) throw new RequestError("Only the church's Website changes the church profile from outside Accounts.", 'WRONG_PRODUCT', 403);
|
||||
const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: r.actor } });
|
||||
if (!known) throw new RequestError("The person making the change isn't someone who signs in to this product.", 'NOT_ALLOWED', 403);
|
||||
try {
|
||||
const church = await updateProfile(ctx, r.church, { ifUpdatedAt: r.ifUpdatedAt });
|
||||
await logRequest(ctx, link, r, 'church_profile_changed_by_product', null, req, { fields: Object.keys(r.church) });
|
||||
return reply({ church });
|
||||
} catch (e) {
|
||||
if (e instanceof ProfileChangedError) throw new RequestError(e.message, 'PROFILE_CHANGED', 409);
|
||||
if (e instanceof ProfileError) throw new RequestError(`${e.message} ${Object.entries(e.fields).map(([k, v]) => `${k}: ${v}`).join('; ')}`.trim(), 'INVALID_REQUEST', 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
case 'church.branding': {
|
||||
const changed = await applyLook(ctx, r.church, r.overwrite);
|
||||
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
|
||||
return reply({ ok: true as const });
|
||||
}
|
||||
case 'messaging.status':
|
||||
return reply(await messagingStatus(ctx));
|
||||
case 'messaging.test':
|
||||
case 'messaging.set': {
|
||||
const save = r.type === 'messaging.set';
|
||||
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
let email: { ok: boolean; error: string | null; saved: boolean } | null = null;
|
||||
let whatsapp: { ok: boolean; error: string | null; saved: boolean } | null = null;
|
||||
if (r.email) {
|
||||
const s = r.email.settings;
|
||||
const pass = s.pass === null ? ((await ctx.settings.get('smtp_pass')) ?? '') : opened(secret, s.pass, 'SMTP password');
|
||||
const tryWith = { host: s.host, port: s.port, secure: s.secure, user: s.user, pass: pass ?? '', from: s.from };
|
||||
try {
|
||||
await ctx.messenger.emailWith(tryWith, { to: r.email.to, ...(await testEmail(ctx, { from: link.product === 'events' ? 'Cross Events' : link.product })) });
|
||||
email = { ok: true, error: null, saved: false };
|
||||
if (save) {
|
||||
await ctx.settings.setMany({ smtp_host: s.host, smtp_port: String(s.port), smtp_secure: String(s.secure), smtp_user: s.user, smtp_from: s.from, ...(s.pass === null ? {} : { smtp_pass: pass }) });
|
||||
email.saved = true;
|
||||
}
|
||||
} catch (e) {
|
||||
email = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
if (r.whatsapp) {
|
||||
const s = r.whatsapp.settings;
|
||||
const token = s.accessToken === null ? ((await ctx.settings.get('wawp_access_token')) ?? '') : opened(secret, s.accessToken, 'WAWP access token');
|
||||
try {
|
||||
if (!token) throw new Error('Give the WAWP access token.');
|
||||
await ctx.messenger.whatsappWith({ accessToken: token, instanceId: s.instanceId }, { to: r.whatsapp.to, text: `This is a test from ${church}'s sign-in. WhatsApp works: sign-in codes can be sent.` });
|
||||
whatsapp = { ok: true, error: null, saved: false };
|
||||
if (save) {
|
||||
await ctx.settings.setMany({ wawp_instance_id: s.instanceId, ...(s.accessToken === null ? {} : { wawp_access_token: token }) });
|
||||
whatsapp.saved = true;
|
||||
}
|
||||
} catch (e) {
|
||||
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 } });
|
||||
}
|
||||
case 'people.newsOff': {
|
||||
const a = await knownAccount(ctx, link, r.sub);
|
||||
const off = r.channel === 'all' ? { email: false, whatsapp: false } : { [r.channel]: false };
|
||||
@@ -314,7 +437,9 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
}
|
||||
const out = await handle(ctx, provider, link, secret, request, req);
|
||||
// Checks write nothing, so they needn't be remembered.
|
||||
const isCheck = 'check' in request && request.check;
|
||||
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
|
||||
// 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(() => {});
|
||||
}
|
||||
@@ -328,6 +453,61 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* The church's look on Accounts' pages from a product's (1.9.0): its name, logo and colours.
|
||||
* `overwrite: false` (a move) fills only what's empty; `true` (an admin's button) replaces them.
|
||||
* Returns the fields changed.
|
||||
*/
|
||||
async function applyLook(ctx: Ctx, look: ChurchLook, overwrite: boolean): Promise<string[]> {
|
||||
type Stored = Record<string, unknown> & { name?: string; branding?: { logoUrl?: string | null; iconUrl?: string | null; colours?: { primary?: string; accent?: string | null } } };
|
||||
const stored = await ctx.settings.json<Stored>('church_profile', {});
|
||||
const branding = { logoUrl: null as string | null, iconUrl: null as string | null, ...(stored.branding ?? {}), colours: { primary: '#1f4e79', accent: '#f2a900', ...(stored.branding?.colours ?? {}) } };
|
||||
const changed: string[] = [];
|
||||
const take = (has: unknown, value: unknown) => value !== null && value !== undefined && value !== '' && (overwrite || !has);
|
||||
const next: Stored = { ...stored };
|
||||
if (take(stored.name, look.name)) { next.name = look.name!; changed.push('name'); }
|
||||
if (take(stored.branding?.logoUrl, look.logoUrl)) { branding.logoUrl = look.logoUrl!; changed.push('logo'); }
|
||||
if (take(stored.branding?.colours?.primary, look.primaryColour)) { branding.colours.primary = look.primaryColour!; changed.push('primary colour'); }
|
||||
if (take(stored.branding?.colours?.accent && stored.branding?.colours?.accent !== '#f2a900', look.accentColour)) { branding.colours.accent = look.accentColour!; changed.push('accent colour'); }
|
||||
if (!changed.length) return changed;
|
||||
next.branding = branding;
|
||||
next.updatedAt = ctx.now().toISOString();
|
||||
await ctx.settings.set('church_profile', JSON.stringify(next));
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** What can be sent now (no secrets), for a product's sign-in settings page. */
|
||||
async function messagingStatus(ctx: Ctx) {
|
||||
const emailReady = await ctx.messenger.emailReady();
|
||||
return {
|
||||
email: { ready: emailReady, host: emailReady ? ((await ctx.settings.get('smtp_host')) || ctx.config.smtp?.host || null) : null, from: emailReady ? ((await ctx.settings.get('smtp_from')) || ctx.config.smtp?.from || null) : null },
|
||||
whatsapp: { ready: await ctx.messenger.whatsappReady(), instanceId: (await ctx.settings.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import type Provider from 'oidc-provider';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError, handle, limit } from '../http.js';
|
||||
import { loginEvent } from '../lib/audit.js';
|
||||
import { confirmNewEmail, emailChangedNotice } from '../lib/emails.js';
|
||||
import { hashPassword, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||
import { emailProblem, normaliseEmail, normalisePhone, profileChanged, setNewsConsent } from '../accounts/service.js';
|
||||
import { confirmTwoFactorSetup, recoveryCodesLeft, replaceRecoveryCodes, startTwoFactorSetup, turnOff } from '../accounts/twoFactor.js';
|
||||
@@ -16,12 +17,22 @@ import { currentNotice } from '../privacy/notice.js';
|
||||
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' };
|
||||
const APP_BLURBS: Record<string, string> = { events: 'Your bookings, tickets and serving', website: 'The church\'s website', app: 'The church app on your phone' };
|
||||
const OPEN_PATHS: Record<string, string> = { events: '/api/auth/signin?returnTo=%2Fdashboard' };
|
||||
const appName = (product: string) => APP_NAMES[product] ?? product;
|
||||
|
||||
export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: number; noticeVersion: number }) {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -44,6 +55,18 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
|
||||
r.get('/me', handle(async (req, res) => view(await signedIn(req, res))));
|
||||
|
||||
// 1.3.0: the church's sites and apps that sign in here, for the account page's quick links.
|
||||
r.get('/me/apps', handle(async (req, res) => {
|
||||
await signedIn(req, res);
|
||||
const [links, listed] = await Promise.all([ctx.db.productLink.findMany({ orderBy: { connectedAt: 'asc' } }), linkedProducts(ctx)]);
|
||||
return {
|
||||
items: links.map((l) => {
|
||||
const url = (listed.find((x) => x.installId === l.installId)?.url ?? l.url).replace(/\/+$/, '');
|
||||
return { id: l.installId, product: l.product, name: appName(l.product), description: APP_BLURBS[l.product] ?? null, url: `${url}${OPEN_PATHS[l.product] ?? '/'}` };
|
||||
}),
|
||||
};
|
||||
}));
|
||||
|
||||
r.put('/me', handle(async (req, res) => {
|
||||
const s = await signedIn(req, res);
|
||||
const name = req.body?.name !== undefined ? String(req.body.name).trim().replace(/\s+/g, ' ') : s.account.name;
|
||||
@@ -60,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);
|
||||
}));
|
||||
|
||||
@@ -74,7 +98,7 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address.', { email: 'Another account uses that email address.' });
|
||||
const token = randomToken();
|
||||
await ctx.db.emailToken.create({ data: { accountId: s.account.id, purpose: `change_email:${email}`, tokenHash: hashToken(token), expiresAt: new Date(ctx.now().getTime() + 24 * 3600e3) } });
|
||||
await ctx.messenger.email({ to: email, subject: 'Confirm your new email address', text: `Confirm this is your new email address for signing in:\n${ctx.config.publicUrl}/account/confirm-email?token=${token}\n\nThe link works for 24 hours.` });
|
||||
await ctx.messenger.email({ to: email, ...(await confirmNewEmail(ctx, { name: s.account.name, url: `${ctx.config.publicUrl}/account/confirm-email?token=${token}` })) });
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
@@ -86,7 +110,7 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address now.');
|
||||
await ctx.db.account.update({ where: { id: s.account.id }, data: { email, emailVerified: true } });
|
||||
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
|
||||
await ctx.messenger.email({ to: s.account.email, subject: 'Your sign-in email address changed', text: `Your account now signs in with ${email}. If you didn't do this, contact the church office straight away.` });
|
||||
await ctx.messenger.email({ to: s.account.email, ...(await emailChangedNotice(ctx, { name: s.account.name, newEmail: email })) });
|
||||
await loginEvent(ctx, s.account.id, 'email_changed', req);
|
||||
await profileChanged(ctx, s.account.id);
|
||||
return view(s);
|
||||
@@ -155,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);
|
||||
|
||||
@@ -9,6 +9,7 @@ import path from 'node:path';
|
||||
import { IDENTITY_SCHEMA, userExportReplySchema } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { onReply, queueCall } from '../links/deliveries.js';
|
||||
import { exportReadyEmail } from '../lib/emails.js';
|
||||
|
||||
const WAIT_MS = 24 * 3600e3;
|
||||
const KEEP_MS = 7 * 24 * 3600e3;
|
||||
@@ -26,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 })) },
|
||||
@@ -71,7 +72,7 @@ export async function finishIfComplete(ctx: Ctx, exportId: string, force = false
|
||||
}, null, 2), { mode: 0o600 });
|
||||
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { status: 'ready', file, readyAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + KEEP_MS) } });
|
||||
const a = await ctx.db.account.findUnique({ where: { id: exp.accountId } });
|
||||
if (a) await ctx.messenger.email({ to: a.email, subject: 'Your data is ready to download', text: `The copy of your data you asked for is ready. Download it from your account page (it's kept for 7 days):\n${ctx.config.publicUrl}/account/privacy` });
|
||||
if (a) await ctx.messenger.email({ to: a.email, ...(await exportReadyEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/account/privacy`, days: Math.round(KEEP_MS / 86400e3) })) });
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,18 +8,79 @@ import { church } from '../church/profile.js';
|
||||
|
||||
export const BUILT_IN_VERSION = 1;
|
||||
|
||||
/**
|
||||
* The built-in notice (1.3.0: in sections, as Cross Events' privacy policy, and saying what
|
||||
* Accounts actually does). Plain text: a line starting "## " is a heading, "• " a bullet. Filled
|
||||
* in from the church profile, so it follows the church's name and contact details.
|
||||
*/
|
||||
export async function builtInNotice(ctx: Ctx) {
|
||||
const c = await church(ctx);
|
||||
const contact = c.contact.email ? ` You can reach us at ${c.contact.email}.` : '';
|
||||
const org = c.name;
|
||||
const contact = [c.contact.email && `• Email: ${c.contact.email}`, c.contact.phone && `• Phone: ${c.contact.phone}`].filter(Boolean) as string[];
|
||||
const keepBackups = (await ctx.settings.get('backup_retain_count')) || '14';
|
||||
return {
|
||||
version: BUILT_IN_VERSION,
|
||||
title: `How ${c.name} looks after your information`,
|
||||
title: `How ${org} looks after your information`,
|
||||
body: [
|
||||
`${c.name} keeps your name, email address and (if you give it) phone number so you can sign in to the church's websites and apps, and so we can contact you about what you've signed up for.`,
|
||||
'We only send you news if you say yes, and you can change that at any time on your account page.',
|
||||
'You can download everything we hold about you, or ask us to delete your account, from your account page. We keep a record of sign-ins to protect your account.',
|
||||
`We don't sell or share your information. The services that store it for us are bound to keep it safe.${contact}`,
|
||||
].join('\n\n'),
|
||||
'## In short',
|
||||
`• Your church account is how you sign in to ${org}'s websites and apps. It holds your name, email address and, if you give it, your mobile number.`,
|
||||
'• Your password is never stored, only a scrambled form of it that can\'t be turned back. Two-step sign-in codes and recovery codes are protected the same way.',
|
||||
'• It\'s kept on the church\'s own server, not shared with other churches, and never sold.',
|
||||
'• The church\'s sites only get your name and contact details, when you sign in to them, and when you change them here.',
|
||||
'• News comes only if you say yes, and you can change that at any time.',
|
||||
'• On your account page you can download everything held about you, see your sign-ins, and delete your account.',
|
||||
'',
|
||||
'## 1. Who we are',
|
||||
`${org} ("we", "us") is responsible for your personal information under the Protection of Personal Information Act (POPIA). This notice is about your church account: the sign-in shared by ${org}'s websites and apps. Each site may hold more about you for what you do there (for example the events site's bookings and tickets), and explains that in its own privacy notice.`,
|
||||
'',
|
||||
'## 2. What we keep',
|
||||
'• Your details: name, email address (and whether you\'ve confirmed it), and your mobile number if you add it.',
|
||||
'• Signing in: your password as a one-way hash, which two-step sign-in method you use, your authenticator app\'s key (encrypted), and your recovery codes (hashed). Codes sent by email or WhatsApp last a few minutes and are never kept in readable form.',
|
||||
'• Security records: when you sign in, fail to, change your password, or turn two-step sign-in on or off, with the time, the IP address, the device type and which site it was for. These let you spot sign-ins you don\'t recognise and let us look into misuse.',
|
||||
'• Your choices: whether you want news by email or WhatsApp, which version of this notice you accepted, and when you made each choice.',
|
||||
'• Which of the church\'s sites you use: so a change to your name or email reaches them, and a deletion is passed on.',
|
||||
'• If you\'re an admin: what you change in the admin pages, in an audit log. When an admin opens someone\'s details, that\'s recorded too.',
|
||||
'',
|
||||
'## 3. How we use it',
|
||||
`• To sign you in, once, to all of ${org}'s sites and apps, and to sign you out of all of them when you sign out or ask to.`,
|
||||
'• To send what signing in needs: email confirmation links, password reset links, sign-in codes, and security notices.',
|
||||
'• To send church news, only if you said yes.',
|
||||
'• To keep your account safe: locking it after too many wrong passwords, and asking admins for a second step.',
|
||||
'',
|
||||
'## 4. Who can see it',
|
||||
`• The church's sites and apps you sign in to get your name, email address and mobile number (and whether they're confirmed), and nothing else from here. Each is listed by the church under Linked products, and only ${org}'s own sites can be linked.`,
|
||||
`• ${org}'s Accounts admins can see your details and recent sign-ins to help you (for example to unlock your account). They can't see your password or codes.`,
|
||||
'• Email is sent through the church\'s email provider, and WhatsApp messages through WAWP (wawp.net); they get only the message and where it goes.',
|
||||
'• The software (Cross Code Accounts) is licensed from Cross Code. Every 15 minutes it sends Cross Code\'s licence server totals, such as how many accounts there are and how many use two-step sign-in, and technical health information. Never names, contact details or anything else about a person.',
|
||||
'• Nobody else, unless South African law requires it. We don\'t sell or rent your information.',
|
||||
'',
|
||||
'## 5. Where it\'s kept, and for how long',
|
||||
`• On ${org}'s server, in its own database, separate from every other church.`,
|
||||
`• Your account and its sign-in history are kept while you have the account. A copy of your data that you ask to download is kept for 7 days. Sign-in codes stop working after a few minutes, and links to set or reset a password after at most 7 days.`,
|
||||
`• The database is backed up every night onto the same server; the last ${keepBackups} backups are kept, then deleted. Backups are only used to put things back after a fault.`,
|
||||
'• When your account is deleted, your name, contact details, password, codes and sign-in history are removed straight away, and are gone from the backups once those backups are deleted in turn.',
|
||||
'',
|
||||
'## 6. Cookies',
|
||||
`Signing in uses a few cookies that are strictly necessary: they keep you signed in (for as long as "Keep me signed in" lasts, if you tick it) and protect each sign-in step. There are no tracking, advertising or analytics cookies, and these pages load nothing from other websites apart from the church's own logo.`,
|
||||
'',
|
||||
'## 7. Your rights',
|
||||
'Under POPIA you may see the information we hold about you, have it corrected or deleted, withdraw consent (for example to news), object to direct marketing, and complain to the Information Regulator. On your account page you can:',
|
||||
'• change your details and your news choices;',
|
||||
'• download a copy of everything the church\'s sites hold about you;',
|
||||
'• see your recent sign-ins, and sign out everywhere;',
|
||||
`• delete your account. You're signed out at once; an admin confirms it, then each of the church's sites deletes what it holds (a site may wait until an event you're booked for is over).`,
|
||||
'We answer requests within 30 days. The Information Regulator: www.inforeg.org.za, enquiries@inforeg.org.za.',
|
||||
'',
|
||||
'## 8. Children',
|
||||
'Anyone under 18 should have a parent\'s or guardian\'s permission to make a church account.',
|
||||
'',
|
||||
'## 9. Changes to this notice',
|
||||
'If this notice changes, you\'re asked to read the new version the next time you sign in.',
|
||||
'',
|
||||
'## 10. Contact us',
|
||||
contact.length ? `To ask about your information or use your rights, contact ${org}:` : `To ask about your information or use your rights, contact ${org}'s office.`,
|
||||
...contact,
|
||||
].join('\n'),
|
||||
publishedAt: null as Date | null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,122 @@
|
||||
// 1.3.0: database backups (Settings → Backups, as Cross Events) and the account page's quick links
|
||||
// to the church's sites.
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import zlib from 'node:zlib';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||
import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, type Dumper } from '../src/backups/backups.js';
|
||||
import { codeAt } from '../src/lib/totp.js';
|
||||
|
||||
let h: Harness;
|
||||
let dir: string;
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'accounts-backups-'));
|
||||
h.ctx.config.backupDir = dir;
|
||||
h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/accounts_test';
|
||||
});
|
||||
after(async () => { await h.close(); fs.rmSync(dir, { recursive: true, force: true }); });
|
||||
|
||||
const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() });
|
||||
const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) });
|
||||
|
||||
async function adminPage() {
|
||||
await h.makeAccount({ email: 'backups.admin@hope.test', password: 'Correct-horse-8', role: 'admin' });
|
||||
const browser = new Browser();
|
||||
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/admin`, (u) => u.pathname === '/signin');
|
||||
const uid = url.searchParams.get('uid')!;
|
||||
await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'backups.admin@hope.test', password: 'Correct-horse-8' });
|
||||
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup`, { method: 'totp' });
|
||||
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
|
||||
await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
|
||||
return browser;
|
||||
}
|
||||
|
||||
describe('backups', () => {
|
||||
test('a backup is the gzipped dump, named as the crosscode script names them', async () => {
|
||||
const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Account" ();\n'));
|
||||
assert.match(b.filename, BACKUP_FILE);
|
||||
assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(dir, b.filename))).toString(), 'CREATE TABLE "Account" ();\n');
|
||||
assert.equal(backupName(new Date(2026, 10, 20, 2, 0, 5)), 'accounts-20261120-020005.sql.gz');
|
||||
// A second one in the same second gets its own name.
|
||||
const again = await runBackup(h.ctx, dumpOf('-- again\n'));
|
||||
assert.notEqual(again.filename, b.filename);
|
||||
});
|
||||
|
||||
test('a dump that fails part-way leaves no file, and says why', async () => {
|
||||
const before = (await listBackups(h.ctx)).length;
|
||||
await assert.rejects(runBackup(h.ctx, failing), /connection refused/);
|
||||
assert.equal((await listBackups(h.ctx)).length, before);
|
||||
assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/);
|
||||
await runBackup(h.ctx, dumpOf('-- fine\n'));
|
||||
assert.equal(await h.ctx.settings.get('backup_last_error'), null);
|
||||
});
|
||||
|
||||
test('only the newest are kept; downloads only by a backup\'s own name', async () => {
|
||||
await h.ctx.settings.set('backup_retain_count', '2');
|
||||
await runBackup(h.ctx, dumpOf('-- newest\n'));
|
||||
const left = await listBackups(h.ctx);
|
||||
assert.equal(left.length, 2);
|
||||
assert.ok(backupPath(h.ctx, left[0]!.filename));
|
||||
assert.equal(backupPath(h.ctx, '../.env'), null);
|
||||
assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null);
|
||||
await h.ctx.settings.set('backup_retain_count', null);
|
||||
});
|
||||
|
||||
test('admins see, change and download them; members can\'t', async () => {
|
||||
await h.makeAccount({ email: 'backups.member@hope.test', password: 'Correct-horse-9' });
|
||||
const member = new Browser();
|
||||
const { url } = await member.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
|
||||
const step = await h.api(member, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'backups.member@hope.test', password: 'Correct-horse-9' });
|
||||
await member.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||
assert.equal((await h.api(member, 'GET', '/api/v2/admin/backups')).status, 403);
|
||||
|
||||
const admin = await adminPage();
|
||||
const list = await h.api(admin, 'GET', '/api/v2/admin/backups');
|
||||
assert.equal(list.status, 200, JSON.stringify(list.body));
|
||||
const items = list.body.items as { filename: string }[];
|
||||
assert.equal(list.body.nightly, true);
|
||||
assert.equal(list.body.retain, 14);
|
||||
const file = await admin.request(`${h.publicUrl}/api/v2/admin/backups/${items[0]!.filename}/download`);
|
||||
assert.equal(file.status, 200);
|
||||
assert.equal(file.headers.get('cache-control'), 'no-store');
|
||||
assert.ok(zlib.gunzipSync(Buffer.from(await file.arrayBuffer())).length > 0);
|
||||
assert.equal((await admin.request(`${h.publicUrl}/api/v2/admin/backups/nope.sql.gz/download`)).status, 404);
|
||||
assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1);
|
||||
|
||||
const bad = await h.api(admin, 'PUT', '/api/v2/admin/backups/settings', { retain: 0, nightly: true });
|
||||
assert.equal(bad.status, 400);
|
||||
const saved = await h.api(admin, 'PUT', '/api/v2/admin/backups/settings', { retain: 30, nightly: false });
|
||||
assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 });
|
||||
assert.equal(await h.ctx.settings.bool('backup_nightly', true), false);
|
||||
});
|
||||
|
||||
test('the nightly backup is skipped while it\'s turned off', async () => {
|
||||
const { runBackupJob } = await import('../src/backups/backups.js');
|
||||
await h.ctx.settings.set('backup_nightly', 'false');
|
||||
assert.deepEqual(await runBackupJob(h.ctx), { skipped: true });
|
||||
await h.ctx.settings.set('backup_nightly', null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('quick links to the church\'s sites', () => {
|
||||
test('the account page lists each connected site, Events opening its dashboard', async () => {
|
||||
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: 'backups.member@hope.test', password: 'Correct-horse-9' });
|
||||
await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||
const apps = await h.api(browser, 'GET', '/api/v2/me/apps');
|
||||
assert.equal(apps.status, 200, JSON.stringify(apps.body));
|
||||
const links = await h.db.productLink.findMany();
|
||||
assert.equal((apps.body.items as unknown[]).length, links.length);
|
||||
for (const item of apps.body.items as { product: string; url: string; name: string }[]) {
|
||||
assert.ok(item.url.startsWith('http'));
|
||||
if (item.product === 'events') assert.match(item.url, /\/api\/auth\/signin\?returnTo=%2Fdashboard$/);
|
||||
}
|
||||
assert.equal((await h.api(new Browser(), 'GET', '/api/v2/me/apps')).status, 401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
// church.update (contracts 1.17.0, Accounts 1.7.0, WEBSITE-1.0-PLAN decision 10): the Website's
|
||||
// admin changes shared profile facts through Accounts, and the brand style is kept by every save.
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { church, mergeProfile, updateProfile } from '../src/church/profile.js';
|
||||
|
||||
const WEBSITE_ID = '7e2a1c3d-9b4f-4d6e-8f70-2b3c4d5e6f70';
|
||||
const EVENTS_ID = '8f3b2d4e-0c5a-4e7f-9a81-3c4d5e6f7a81';
|
||||
let h: Harness;
|
||||
const secrets: Record<string, string> = {};
|
||||
let editor: string;
|
||||
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
for (const [id, product] of [[WEBSITE_ID, 'website'], [EVENTS_ID, 'events']] as const) {
|
||||
secrets[id] = newLinkSecret();
|
||||
await h.db.productLink.create({
|
||||
data: { installId: id, product, url: `https://${product}.hope.test`, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secrets[id]!), connectedAt: new Date() },
|
||||
});
|
||||
}
|
||||
const a = await h.makeAccount({ email: 'editor@hope.test' });
|
||||
editor = a.id as string;
|
||||
for (const linkId of [WEBSITE_ID, EVENTS_ID]) await h.db.productPerson.create({ data: { linkId, accountId: editor, via: 'sign_in', createdAt: new Date() } });
|
||||
await updateProfile(h.ctx, { name: 'Hope Family Church', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } } });
|
||||
});
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
async function ask(body: Record<string, unknown>, from = WEBSITE_ID) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: editor, type: 'church.update', ...body });
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret: secrets[from]!, rawBody: raw });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
describe('church.update from the Website', () => {
|
||||
test('changes only the style, keeps the colours and logo, and goes live at once', async () => {
|
||||
const res = await ask({ church: { branding: { style: { fontPairing: 'warm', corners: 'round' } } } });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
const c = await church(h.ctx);
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'round' });
|
||||
assert.equal(c.branding.colours.primary, '#1f4e79');
|
||||
assert.equal(c.name, 'Hope Family Church');
|
||||
assert.deepEqual((res.body.church as { branding: unknown }).branding, c.branding);
|
||||
});
|
||||
|
||||
test('tells every linked product the profile changed, and audits it as the editor', async () => {
|
||||
const before = await h.db.delivery.count();
|
||||
const res = await ask({ church: { shortName: 'Hope Family' } });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.ok((await h.db.delivery.count()) > before);
|
||||
const log = await h.db.auditLog.findFirst({ where: { action: 'church_profile_changed_by_product' }, orderBy: { createdAt: 'desc' } });
|
||||
assert.equal(log?.actorId, editor);
|
||||
});
|
||||
|
||||
test('refuses another product, someone who doesn\'t sign in through the Website, and a stale edit', async () => {
|
||||
const events = await ask({ church: { name: 'Hijacked' } }, EVENTS_ID);
|
||||
assert.equal(events.status, 403);
|
||||
assert.equal(events.body.code, 'WRONG_PRODUCT');
|
||||
|
||||
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
|
||||
const notKnown = await ask({ actor: stranger.id as string, church: { name: 'Hijacked' } });
|
||||
assert.equal(notKnown.status, 403);
|
||||
assert.equal(notKnown.body.code, 'NOT_ALLOWED');
|
||||
|
||||
const stale = await ask({ ifUpdatedAt: '2020-01-01T00:00:00.000Z', church: { name: 'Hijacked' } });
|
||||
assert.equal(stale.status, 409);
|
||||
assert.equal(stale.body.code, 'PROFILE_CHANGED');
|
||||
assert.equal((await church(h.ctx)).name, 'Hope Family Church');
|
||||
});
|
||||
|
||||
test('takes an edit made on the current version', async () => {
|
||||
const current = await church(h.ctx);
|
||||
const res = await ask({ ifUpdatedAt: current.updatedAt, church: { serviceTimes: [{ day: 'sunday', time: '09:00', label: null, campus: null, note: null }] } });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.equal((await church(h.ctx)).serviceTimes.length, 1);
|
||||
});
|
||||
|
||||
test('an invalid value is refused with what\'s wrong', async () => {
|
||||
const res = await ask({ church: { contact: { email: null, phone: '016 123', whatsapp: null, address: null } } });
|
||||
assert.equal(res.status, 400);
|
||||
assert.equal(res.body.code, 'INVALID_REQUEST');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving the profile keeps the brand style', () => {
|
||||
test('an admin form that sends branding without the style doesn\'t drop it', async () => {
|
||||
await updateProfile(h.ctx, { branding: { style: { fontPairing: 'classic', corners: 'sharp' } } });
|
||||
await updateProfile(h.ctx, { branding: { logoUrl: null, iconUrl: null, colours: { primary: '#204060', accent: null } } });
|
||||
const c = await church(h.ctx);
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'classic', corners: 'sharp' });
|
||||
assert.equal(c.branding.colours.primary, '#204060');
|
||||
});
|
||||
|
||||
test('mergeProfile replaces other fields whole and merges branding', () => {
|
||||
const merged = mergeProfile({ name: 'A', social: [1], branding: { logoUrl: 'x', colours: { primary: '#000000' } } }, { social: [], branding: { colours: { primary: '#ffffff' } } });
|
||||
assert.deepEqual(merged, { name: 'A', social: [], branding: { logoUrl: 'x', colours: { primary: '#ffffff' } } });
|
||||
});
|
||||
|
||||
test('the sign-in pages get the style', async () => {
|
||||
const res = await fetch(`${h.publicUrl}/api/v2/branding`);
|
||||
const b = (await res.json()) as { style: unknown };
|
||||
assert.deepEqual(b.style, { fontPairing: 'classic', corners: 'sharp' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
// Accounts 1.9.0: a demo scenario's church and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { CHURCH_PATHS, churchSchema } from '@crosscode/contracts';
|
||||
import { demoPeople } from '@crosscode/demo';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { loadScenario } from '../src/demo/scenario.js';
|
||||
import { church } from '../src/church/profile.js';
|
||||
import { verifyPassword } from '../src/lib/passwords.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
const live = async () => h.db.account.findMany({ where: { status: { not: 'deleted' } } });
|
||||
|
||||
describe('loading a demo scenario', () => {
|
||||
test('the church becomes the scenario\'s, with its own logo and icon, and the products are told', async () => {
|
||||
const real = await h.makeAccount({ email: 'office@hope.test' });
|
||||
const admin = await h.makeAccount({ email: 'admin.demo@example.com', role: 'admin' });
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.church, 'Acacia Hill Church');
|
||||
const c = await church(h.ctx);
|
||||
assert.ok(churchSchema.safeParse(c).success);
|
||||
assert.equal(c.name, 'Acacia Hill Church');
|
||||
assert.equal(c.shortName, 'Acacia Hill');
|
||||
assert.equal(c.branding.colours.primary, '#2f6f4f');
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'soft' });
|
||||
assert.equal(c.branding.logoUrl, `${h.publicUrl}/api/demo-assets/community-family/logo.svg`);
|
||||
assert.equal(c.contact.email, 'office.acaciahill@example.com');
|
||||
assert.ok((await h.db.delivery.findMany({ where: { type: 'church.changed' } })).length >= 1);
|
||||
// Real people and admins are never touched.
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: real.id } }))!.status, 'active');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: admin.id } }))!.status, 'active');
|
||||
});
|
||||
|
||||
test('every person has an account with the id the other products work out, and the demo password', async () => {
|
||||
const people = demoPeople('community-family');
|
||||
const ids = new Set((await live()).map((a) => a.id));
|
||||
for (const p of people) assert.ok(ids.has(p.id), p.email);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: people[0]!.id } }))!;
|
||||
assert.equal(pastor.name, 'Thabo Nkosi');
|
||||
assert.equal(pastor.emailVerified, true);
|
||||
assert.ok(await verifyPassword('Demo@1234', pastor.passwordHash as string));
|
||||
});
|
||||
|
||||
test('loading it again changes nobody\'s id', async () => {
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.created, 0);
|
||||
assert.equal(r.removed, 0);
|
||||
assert.equal(r.updated, demoPeople('community-family').length);
|
||||
});
|
||||
|
||||
test('another scenario replaces the demo people; switching back brings them back with the same ids', async () => {
|
||||
const before = demoPeople('community-family');
|
||||
const r = await loadScenario(h.ctx, 'bold-plant');
|
||||
assert.equal(r.church, 'Harbour City Church');
|
||||
assert.equal(r.removed, before.length);
|
||||
assert.equal(r.created, demoPeople('bold-plant').length);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: before[0]!.id } }))!.status, 'deleted');
|
||||
assert.ok(await h.db.account.findUnique({ where: { email: 'office@hope.test' } }), 'a real person stays');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'admin.demo@example.com' } }))!.status, 'active', 'an admin stays');
|
||||
|
||||
const back = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(back.updated, before.length);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: before[0]!.id } }))!;
|
||||
assert.equal(pastor.status, 'active');
|
||||
assert.equal(pastor.email, before[0]!.email);
|
||||
});
|
||||
|
||||
test('a scenario with campuses has them in the profile', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church' }));
|
||||
// Riverside has about 2 450 people; only its profile is checked here.
|
||||
const c = await (async () => { await loadScenario(h.ctx, 'clean-campus'); return church(h.ctx); })();
|
||||
assert.deepEqual(c.campuses.map((x) => x.slug), ['stellenbosch', 'paarl', 'somerset-west']);
|
||||
assert.equal(c.serviceTimes.filter((s) => s.campus === 'stellenbosch').length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('demo logos', () => {
|
||||
test('served as SVG for a scenario, 404 for anything else', async () => {
|
||||
const res = await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/icon.svg`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get('content-type'), 'image/svg+xml; charset=utf-8');
|
||||
assert.match(await res.text(), /^<svg[^>]*>.*#e4572e/);
|
||||
const logo = await (await fetch(`${h.publicUrl}/api/demo-assets/heritage-parish/logo.svg`)).text();
|
||||
assert.match(logo, /St Columba'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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
// 1.4.0: Admin → Background jobs (switch a job on or off, change its schedule, over the .env) and
|
||||
// the styled emails (as Cross Events').
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||
import { codeAt } from '../src/lib/totp.js';
|
||||
import { JOBS, cronFor, isEnabled, useEnvForTest } from '../src/jobs.js';
|
||||
import { esc, newAccountEmail, resetPasswordEmail } from '../src/lib/emails.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { useEnvForTest(process.env); await h.close(); });
|
||||
|
||||
let adminBrowser: Browser | null = null;
|
||||
async function adminPage() {
|
||||
if (adminBrowser) return adminBrowser;
|
||||
await h.makeAccount({ email: 'jobs.admin@hope.test', password: 'Correct-horse-8', role: 'admin' });
|
||||
const browser = new Browser();
|
||||
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/admin`, (u) => u.pathname === '/signin');
|
||||
const uid = url.searchParams.get('uid')!;
|
||||
await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'jobs.admin@hope.test', password: 'Correct-horse-8' });
|
||||
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup`, { method: 'totp' });
|
||||
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
|
||||
await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
|
||||
adminBrowser = browser;
|
||||
return browser;
|
||||
}
|
||||
|
||||
const backup = JOBS.find((j) => j.name === 'backup')!;
|
||||
|
||||
describe('background jobs', () => {
|
||||
test('the .env flag and schedule apply until an admin chooses; their choice wins; null goes back', async () => {
|
||||
useEnvForTest({ BACKUP_ENABLED: 'false', JOB_SCHEDULE_BACKUP: '30 1 * * *' });
|
||||
h.ctx.config.jobsEnabled = true; // the harness turns them off; nothing is started here either way
|
||||
const browser = await adminPage();
|
||||
let list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
|
||||
assert.equal(list.status, 200);
|
||||
let job = (list.body.jobs as { name: string; enabled: boolean; envEnabled: boolean; cron: string; override: { enabled: boolean | null; cron: string | null } }[]).find((j) => j.name === 'backup')!;
|
||||
assert.equal(job.enabled, false);
|
||||
assert.equal(job.envEnabled, false);
|
||||
assert.equal(job.cron, '30 1 * * *');
|
||||
assert.deepEqual(job.override, { enabled: null, cron: null });
|
||||
|
||||
const on = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: true, cron: '0 3 * * *' });
|
||||
assert.equal(on.status, 200);
|
||||
assert.deepEqual(on.body.override, { enabled: true, cron: '0 3 * * *' });
|
||||
assert.equal(isEnabled(h.ctx, backup), true);
|
||||
assert.equal(cronFor(h.ctx, backup), '0 3 * * *');
|
||||
list = await h.api(browser, 'GET', '/api/v2/admin/jobs');
|
||||
job = (list.body.jobs as typeof job[]).find((j) => j.name === 'backup')!;
|
||||
assert.equal(job.enabled, true);
|
||||
assert.equal(job.envEnabled, false);
|
||||
|
||||
const back = await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: null, cron: null });
|
||||
assert.deepEqual(back.body.override, { enabled: null, cron: null });
|
||||
assert.equal(isEnabled(h.ctx, backup), false);
|
||||
assert.equal(cronFor(h.ctx, backup), '30 1 * * *');
|
||||
|
||||
const audit = await h.ctx.db.auditLog.findMany({ where: { action: 'job_settings_changed' } });
|
||||
assert.equal(audit.length, 2);
|
||||
});
|
||||
|
||||
test('a bad schedule, a bad switch and an unknown job are refused', async () => {
|
||||
const browser = await adminPage();
|
||||
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { cron: 'every night' })).status, 400);
|
||||
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/backup', { enabled: 'yes' })).status, 400);
|
||||
assert.equal((await h.api(browser, 'PUT', '/api/v2/admin/jobs/nope', { enabled: true })).status, 404);
|
||||
});
|
||||
|
||||
test('only admins see them', async () => {
|
||||
const anon = new Browser();
|
||||
assert.equal((await h.api(anon, 'GET', '/api/v2/admin/jobs')).status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('styled emails', () => {
|
||||
test('in the church colour, with its name escaped, and the same plain text as before', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope <Church> & Co', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#336699', accent: null } }, contact: { email: 'office@hope.test', phone: null, whatsapp: null, address: null } }));
|
||||
const r = await resetPasswordEmail(h.ctx, { name: '<b>Jane</b>', url: 'https://accounts.hope.test/reset?token=abc', minutes: 60 });
|
||||
assert.equal(r.subject, 'Reset your password');
|
||||
assert.match(r.text, /https:\/\/accounts\.hope\.test\/reset\?token=abc/);
|
||||
assert.match(r.html, /background-color:#336699/);
|
||||
assert.match(r.html, /Hope <Church> & Co/);
|
||||
assert.ok(!r.html.includes('<b>Jane</b>'));
|
||||
assert.match(r.html, /href="https:\/\/accounts\.hope\.test\/reset\?token=abc"/);
|
||||
assert.match(r.html, /office@hope\.test/);
|
||||
const n = await newAccountEmail(h.ctx, { name: 'Sam', url: 'javascript:alert(1)', days: 7 });
|
||||
assert.equal(n.subject, 'Your account at Hope <Church> & Co');
|
||||
assert.ok(!n.html.includes('href="javascript:'));
|
||||
assert.equal(esc('"x"'), '"x"');
|
||||
});
|
||||
|
||||
test('the test email from admin goes as HTML too', async () => {
|
||||
const browser = await adminPage();
|
||||
const m = h.ctx.messenger as MemoryMessenger;
|
||||
const before = m.emails.length;
|
||||
assert.equal((await h.api(browser, 'POST', '/api/v2/admin/settings/test-email', {})).status, 200);
|
||||
const sent = m.emails.slice(before).at(-1)!;
|
||||
assert.equal(sent.subject, 'Test email from Accounts');
|
||||
assert.match(sent.html ?? '', /<!DOCTYPE html>/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
// Accounts 1.2.0: sign-in never fails with a 500 when a code can't be sent, WhatsApp codes fall back
|
||||
// to email, and a linked product can check, test and set Accounts' email and WhatsApp
|
||||
// (crosscode.identity-request/1 messaging.*, contracts 1.9.0).
|
||||
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 } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, startHarness, type Harness } from './support/harness.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
|
||||
let h: Harness;
|
||||
let secret: string;
|
||||
let messenger: MemoryMessenger;
|
||||
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
messenger = h.messenger as MemoryMessenger;
|
||||
secret = newLinkSecret();
|
||||
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
|
||||
});
|
||||
after(async () => { await h.close(); });
|
||||
beforeEach(() => { messenger.emailOn = true; messenger.whatsappOn = false; messenger.failHost = null; });
|
||||
|
||||
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: EVENTS_ID, secret, rawBody: raw }) } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const smtp = (over: Record<string, unknown> = {}) => ({ host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', pass: sealLinkValue(secret, 'mail-pass'), from: 'events@hope.test', ...over });
|
||||
|
||||
describe('a code that can\'t be sent', () => {
|
||||
test('without email, the page says so (503 with a message), never a 500', async () => {
|
||||
messenger.emailOn = false;
|
||||
await h.makeAccount({ email: 'unverified@hope.test', password: 'Correct-horse-1', emailVerified: false });
|
||||
const r = await h.signIn(new Browser(), 'unverified@hope.test', 'Correct-horse-1');
|
||||
// The password step answers with the error of the next step: the email code couldn't go.
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.error && (r.pending.error as { code: string }).code, 'CODE_NOT_SENT', JSON.stringify(r.pending));
|
||||
});
|
||||
|
||||
test('a WhatsApp code that can\'t go is sent by email', async () => {
|
||||
await h.makeAccount({ email: 'wa@hope.test', password: 'Correct-horse-1', phone: '+27821230000', twoFactorMethod: 'whatsapp' });
|
||||
const r = await h.signIn(new Browser(), 'wa@hope.test', 'Correct-horse-1');
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.stage, 'two_factor', JSON.stringify(r.pending));
|
||||
assert.match(String(r.pending.sentTo), /@hope\.test$/);
|
||||
assert.ok(messenger.lastCode('wa@hope.test'));
|
||||
});
|
||||
|
||||
test('forgot password says email isn\'t set up, for any address', async () => {
|
||||
messenger.emailOn = false;
|
||||
const res = await h.api(new Browser(), 'POST', '/api/v2/password/forgot', { email: 'nobody@hope.test' });
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal((res.body.error as { code: string }).code, 'EMAIL_NOT_READY');
|
||||
});
|
||||
});
|
||||
|
||||
describe('messaging.* from a product', () => {
|
||||
test('status says what can be sent, without secrets', async () => {
|
||||
messenger.emailOn = false;
|
||||
const r = await ask({ type: 'messaging.status' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.deepEqual(r.body.email, { ready: false, host: null, from: null });
|
||||
assert.equal(JSON.stringify(r.body).includes('pass'), false);
|
||||
});
|
||||
|
||||
test('test sends with the settings given and saves nothing; a failure says why', async () => {
|
||||
const ok = await ask({ type: 'messaging.test', email: { settings: smtp(), to: 'office@hope.test' } });
|
||||
assert.deepEqual(ok.body.email, { ok: true, error: null, saved: false });
|
||||
assert.deepEqual(messenger.tried.at(-1), { kind: 'email', settings: { host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', pass: 'mail-pass', from: 'events@hope.test' }, to: 'office@hope.test' });
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null);
|
||||
messenger.failHost = 'bad.hope.test';
|
||||
const bad = await ask({ type: 'messaging.test', email: { settings: smtp({ host: 'bad.hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((bad.body.email as { ok: boolean }).ok, false);
|
||||
assert.match(String((bad.body.email as { error: string }).error), /ECONNREFUSED/);
|
||||
});
|
||||
|
||||
test('set saves only what worked, with the password encrypted; null keeps the saved password', async () => {
|
||||
messenger.failHost = 'bad.hope.test';
|
||||
const failed = await ask({ type: 'messaging.set', email: { settings: smtp({ host: 'bad.hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((failed.body.email as { saved: boolean }).saved, false);
|
||||
assert.equal(await h.ctx.settings.get('smtp_host'), null);
|
||||
|
||||
const saved = await ask({ type: 'messaging.set', email: { settings: smtp(), to: 'office@hope.test' }, whatsapp: { settings: { accessToken: sealLinkValue(secret, 'wawp-token'), instanceId: 'INST1' }, to: '+27821234567' } });
|
||||
assert.deepEqual([saved.body.email, saved.body.whatsapp].map((x) => (x as { saved: boolean }).saved), [true, true]);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'mail-pass');
|
||||
const row = await h.db.appSetting.findUnique({ where: { key: 'smtp_pass' } });
|
||||
assert.notEqual(row!.value, 'mail-pass', 'encrypted at rest');
|
||||
assert.equal(await h.ctx.settings.get('wawp_instance_id'), 'INST1');
|
||||
|
||||
const kept = await ask({ type: 'messaging.set', email: { settings: smtp({ pass: null, from: 'office@hope.test' }), to: 'office@hope.test' } });
|
||||
assert.equal((kept.body.email as { saved: boolean }).saved, true);
|
||||
assert.equal(await h.ctx.settings.get('smtp_pass'), 'mail-pass');
|
||||
assert.equal(await h.ctx.settings.get('smtp_from'), 'office@hope.test');
|
||||
});
|
||||
|
||||
test('people.ensure still makes the account when its email can\'t go, and says so', async () => {
|
||||
messenger.emailOn = false;
|
||||
const r = await ask({ type: 'people.ensure', name: 'No Mail', email: 'nomail@hope.test', phone: null, returnUrl: 'https://events.hope.test/' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.created, true);
|
||||
assert.equal(r.body.emailSent, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the church\'s look from a product (1.9.0)', () => {
|
||||
test('a move fills only what\'s empty; the button replaces it', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope' }));
|
||||
const look = { name: 'Other Name', primaryColour: '#123456', accentColour: '#abcdef', logoUrl: 'https://events.hope.test/uploads/logo.png' };
|
||||
assert.equal((await ask({ type: 'church.branding', church: look, overwrite: false })).status, 200);
|
||||
const filled = await h.ctx.settings.json<{ name: string; branding: { logoUrl: string; colours: { primary: string; accent: string } } }>('church_profile', {} as never);
|
||||
assert.equal(filled.name, 'Hope Family Church', 'kept');
|
||||
assert.equal(filled.branding.logoUrl, 'https://events.hope.test/uploads/logo.png');
|
||||
assert.equal(filled.branding.colours.primary, '#123456');
|
||||
await ask({ type: 'church.branding', church: { ...look, primaryColour: '#654321', logoUrl: 'https://events.hope.test/new.png' }, overwrite: true });
|
||||
const replaced = await h.ctx.settings.json<{ name: string; branding: { logoUrl: string; colours: { primary: string } } }>('church_profile', {} as never);
|
||||
assert.deepEqual([replaced.name, replaced.branding.logoUrl, replaced.branding.colours.primary], ['Other Name', 'https://events.hope.test/new.png', '#654321']);
|
||||
// The sign-in pages get it.
|
||||
const b = await h.api(new Browser(), 'GET', '/api/v2/branding');
|
||||
assert.equal(b.body.logoUrl, 'https://events.hope.test/new.png');
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@
|
||||
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
|
||||
// church profile, Connect, and admin and setup rules.
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
|
||||
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
|
||||
@@ -156,6 +158,44 @@ describe('Connect from a product', () => {
|
||||
const client = await h.provider.Client.find(APP_ID);
|
||||
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
|
||||
});
|
||||
|
||||
test('1.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
|
||||
let clock = new Date('2026-11-26T15:00:00Z');
|
||||
const own = await startHarness({ now: () => clock });
|
||||
const appKey = generateEd25519();
|
||||
const NEW_ID = '5c1d7e2f-8a3b-4c4d-9e5f-6a7b8c9d0e1f';
|
||||
const listed = { product: 'website', installId: NEW_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) };
|
||||
// A Hub whose list has the new Website; Accounts' cached list doesn't yet.
|
||||
const hubCalls: string[] = [];
|
||||
const hub = http.createServer((req, res) => {
|
||||
hubCalls.push(String(req.url));
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: [listed] }));
|
||||
});
|
||||
await new Promise<void>((r) => hub.listen(0, '127.0.0.1', () => r()));
|
||||
try {
|
||||
own.ctx.config.hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
|
||||
await own.ctx.settings.setMany({ hub_install_secret: 'secret', hub_linked_products: '[]' });
|
||||
const msg = (installId: string) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'website', installId, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: clock.toISOString(), nonce: newLinkNonce() }, appKey.privateKeyPem);
|
||||
const send = (installId: string) => fetch(`${own.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(installId)) });
|
||||
|
||||
assert.equal((await send(NEW_ID)).status, 200, 'linked at once');
|
||||
assert.deepEqual(hubCalls, ['/api/installs/heartbeat']);
|
||||
assert.equal(await own.db.productLink.count({ where: { installId: NEW_ID } }), 1);
|
||||
|
||||
// An install the Hub doesn't list: refused, and within the minute the Hub isn't asked again.
|
||||
const UNKNOWN = '7e3f9a4b-0c5d-4e6f-8a7b-9c0d1e2f3a4b';
|
||||
assert.equal((await send(UNKNOWN)).status, 403);
|
||||
assert.equal((await send(UNKNOWN)).status, 403);
|
||||
assert.equal(hubCalls.length, 1);
|
||||
clock = new Date(clock.getTime() + 61_000);
|
||||
assert.equal((await send(UNKNOWN)).status, 403);
|
||||
assert.equal(hubCalls.length, 2);
|
||||
} finally {
|
||||
await new Promise((r) => hub.close(r));
|
||||
await own.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin and setup', () => {
|
||||
|
||||
@@ -177,6 +177,51 @@ describe('people.* from a product', () => {
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.status, 'deactivated');
|
||||
});
|
||||
|
||||
test('people.removeDemo removes only the product\'s demo people, never an admin or a real address', async () => {
|
||||
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
|
||||
const demo = await ensure('Old Demo', 'old.demo@example.com');
|
||||
const real = await ensure('Real Person', 'real.person@hope.test');
|
||||
const demoAdmin = await ensure('Demo Admin', 'demo.admin@example.com');
|
||||
await h.db.account.update({ where: { id: demoAdmin }, data: { role: 'admin' } });
|
||||
const stranger = (await h.makeAccount({ email: 'not.known@example.com' })).id;
|
||||
|
||||
const res = await ask({ type: 'people.removeDemo', subs: [demo, real, demoAdmin, stranger] });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.equal(res.body.removed, 1);
|
||||
assert.deepEqual(res.body.kept, [{ sub: real, reason: 'not_demo' }, { sub: demoAdmin, reason: 'admin' }, { sub: stranger, reason: 'unknown' }]);
|
||||
const gone = (await h.db.account.findUnique({ where: { id: demo } }))!;
|
||||
assert.equal(gone.status, 'deleted');
|
||||
assert.notEqual(gone.email, 'old.demo@example.com', 'the address is free for the next demo');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: real } }))!.status, 'active');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: stranger } }))!.status, 'active');
|
||||
// The next demo can have the same person again, as a new account.
|
||||
const again = await ask({ type: 'people.ensure', name: 'Old Demo', email: 'old.demo@example.com', phone: null, returnUrl: 'https://events.hope.test/' });
|
||||
assert.equal(again.body.created, true);
|
||||
});
|
||||
|
||||
test('1.5.0 people.check: profiles of the product\'s people, deleted accounts, and unknown for the rest; never stored', async () => {
|
||||
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
|
||||
const known = await ensure('Check Known', 'check.known@hope.test');
|
||||
const gone = await ensure('Check Gone', 'check.gone@hope.test');
|
||||
await h.db.account.update({ where: { id: gone }, data: { status: 'deleted' } });
|
||||
const off = await ensure('Check Off', 'check.off@hope.test');
|
||||
await h.db.account.update({ where: { id: off }, data: { status: 'deactivated' } });
|
||||
const stranger = (await h.makeAccount({ email: 'check.stranger@hope.test' })).id as string;
|
||||
const nobody = crypto.randomUUID();
|
||||
const requestId = crypto.randomUUID();
|
||||
const res = await ask({ type: 'people.check', subs: [known, gone, off, stranger, nobody] }, { requestId });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
const bySub = Object.fromEntries((res.body.people as { sub: string; status: string; profile: { name: string } | null }[]).map((p) => [p.sub, p]));
|
||||
assert.equal(bySub[known]!.status, 'active');
|
||||
assert.equal(bySub[known]!.profile!.name, 'Check Known');
|
||||
assert.equal(bySub[gone]!.status, 'deleted');
|
||||
assert.equal(bySub[gone]!.profile, null);
|
||||
assert.equal(bySub[off]!.status, 'deactivated');
|
||||
assert.deepEqual([bySub[stranger]!.status, bySub[stranger]!.profile], ['unknown', null], 'not known through this product: no profile');
|
||||
assert.equal(bySub[nobody]!.status, 'unknown');
|
||||
assert.equal(await h.db.productRequest.findUnique({ where: { requestId } }), null, 'the reply holds profiles: not kept');
|
||||
});
|
||||
|
||||
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
|
||||
const requestId = crypto.randomUUID();
|
||||
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// 1.6.0: a "New sign-in" email (and WhatsApp) after each sign-in, as Cross Events sends.
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { describeDevice, sendSignInNotice } from '../src/accounts/signInNotice.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
const CHROME_WIN = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
|
||||
|
||||
describe('sign-in notices', () => {
|
||||
test('an email with when, where, the device and the site; WhatsApp too for a verified number', async () => {
|
||||
const m = h.ctx.messenger as MemoryMessenger;
|
||||
const a = await h.makeAccount({ email: 'notice.person@hope.test' });
|
||||
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: '127.0.0.1', userAgent: CHROME_WIN, clientId: 'accounts-self' }), 'sent');
|
||||
const mail = m.emails.filter((e) => e.to === 'notice.person@hope.test').at(-1)!;
|
||||
assert.match(mail.subject, /^New sign-in to your .+ account$/);
|
||||
assert.match(mail.text, /Device: Chrome on Windows/);
|
||||
assert.match(mail.text, /Signed in to: Your account page/);
|
||||
assert.match(mail.html ?? '', /Not you\?/);
|
||||
|
||||
await h.db.account.update({ where: { id: a.id as string }, data: { phone: '+27821234567', phoneVerified: true } });
|
||||
m.whatsappOn = true;
|
||||
const before = m.whatsapps.length;
|
||||
await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null });
|
||||
assert.equal(m.whatsapps.length, before + 1);
|
||||
assert.match(m.whatsapps.at(-1)!.text, /New sign-in/);
|
||||
m.whatsappOn = false;
|
||||
});
|
||||
|
||||
test('admins can switch them off; a failing email never throws', async () => {
|
||||
const m = h.ctx.messenger as MemoryMessenger;
|
||||
const a = await h.makeAccount({ email: 'notice.off@hope.test' });
|
||||
await h.ctx.settings.set('signin_notices', 'false');
|
||||
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'off');
|
||||
await h.ctx.settings.set('signin_notices', null);
|
||||
m.emailOn = false;
|
||||
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'failed');
|
||||
m.emailOn = true;
|
||||
});
|
||||
|
||||
test('device names', () => {
|
||||
assert.equal(describeDevice(CHROME_WIN), 'Chrome on Windows');
|
||||
assert.equal(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1'), 'Safari on iPhone or iPad');
|
||||
assert.equal(describeDevice(null), 'Unknown device');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// 1.7.0 (WEBSITE-1.0-PLAN §3, §9): the church's brand style and shared footer on Accounts' public
|
||||
// pages. The e2e church (e2e/server.ts) has the "warm" pairing, round corners and service times.
|
||||
const PRODUCT = "http://localhost:5211";
|
||||
|
||||
test("the sign-in page uses the church's fonts and corners, and shows its footer", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
|
||||
|
||||
const heading = page.getByRole("heading", { name: "Sign in to Hope Family Church" });
|
||||
expect(await heading.evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Fraunces");
|
||||
expect(await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Nunito Sans");
|
||||
// The font files themselves load from this site (self-hosted), not from anyone else.
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
expect(await page.evaluate(() => document.fonts.check('600 20px "CC Fraunces"'))).toBe(true);
|
||||
expect(await page.getByRole("button", { name: "Sign in" }).evaluate((el) => getComputedStyle(el).borderRadius)).toBe("9999px");
|
||||
|
||||
const footer = page.locator("footer");
|
||||
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
|
||||
await expect(footer).toContainText("Sundays 09:00");
|
||||
await expect(footer.getByRole("link", { name: "office@hope.test" })).toHaveAttribute("href", "mailto:office@hope.test");
|
||||
await expect(footer.getByRole("link", { name: "Website" })).toHaveAttribute("href", PRODUCT);
|
||||
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/privacy");
|
||||
});
|
||||
|
||||
test("fonts never come from another site", async ({ page }) => {
|
||||
const foreign: string[] = [];
|
||||
page.on("request", (r) => { if (/\.(woff2?|ttf|otf)(\?|$)/.test(r.url()) && !r.url().startsWith("http://localhost:3210/")) foreign.push(r.url()); });
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
expect(foreign).toEqual([]);
|
||||
});
|
||||
|
||||
test("the sign-in page with the footer passes axe (WCAG 2.2 AA)", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await expect(page.locator("footer")).toBeVisible();
|
||||
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
|
||||
});
|
||||
@@ -29,7 +29,13 @@ const messenger = new MemoryMessenger();
|
||||
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
|
||||
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
|
||||
// 1.7.0: a brand style, service times and contact details, so the pages show the church's fonts and footer.
|
||||
church_profile: JSON.stringify({
|
||||
name: 'Hope Family Church', shortName: 'Hope',
|
||||
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' }, style: { fontPairing: 'warm', corners: 'round' } },
|
||||
serviceTimes: [{ day: 'sunday', time: '09:00', label: 'Morning service', campus: null, note: null }],
|
||||
contact: { email: 'office@hope.test', phone: '+27161234567', whatsapp: null, address: null },
|
||||
}),
|
||||
});
|
||||
const linkSecret = newLinkSecret();
|
||||
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
|
||||
|
||||
@@ -76,13 +76,17 @@ test("a product asking for two-step sign-in: set up with an app, recovery codes,
|
||||
await expect(page.locator("#amr")).toHaveText("pwd otp mfa");
|
||||
});
|
||||
|
||||
test("the account page: signs in first, then saves details", async ({ page }) => {
|
||||
test("the account page: signs in first, links to the church's sites, then saves details", async ({ page }) => {
|
||||
await page.goto("/account");
|
||||
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||
await page.getByLabel("Email address").fill("new@hope.test");
|
||||
await page.getByLabel("Password").fill("Correct-horse-2");
|
||||
await page.getByRole("button", { name: "Sign in" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Your account" })).toBeVisible();
|
||||
await expect(page.getByRole("heading", { name: "Hi, New" })).toBeVisible();
|
||||
// 1.3.0: a quick link to each site that signs in here (the test product is a website).
|
||||
await expect(page.getByRole("link", { name: /Website/ })).toHaveAttribute("href", "http://localhost:5211/");
|
||||
await page.getByRole("navigation", { name: "Your account" }).getByRole("link", { name: "Your details" }).click();
|
||||
await expect(page).toHaveURL(/\/account\/details$/);
|
||||
await page.getByLabel("Name").fill("New Person-Smith");
|
||||
await page.getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Your details are saved");
|
||||
@@ -98,6 +102,14 @@ test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
|
||||
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
|
||||
await page.getByRole("button", { name: "Turn on" }).click();
|
||||
await page.getByRole("button", { name: "I've saved them" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Accounts admin" })).toBeVisible();
|
||||
// 1.8.0: /admin is the overview, with a tile for every section; People is one.
|
||||
await expect(page.getByRole("heading", { name: "Admin", level: 1 })).toBeVisible();
|
||||
await expect(page.getByText("People with an account")).toBeVisible();
|
||||
await page.getByRole("navigation", { name: "Admin" }).getByRole("link", { name: "People", exact: true }).click();
|
||||
await expect(page.getByRole("heading", { name: "People", level: 1 })).toBeVisible();
|
||||
await expect(page.getByText("thandi@hope.test")).toBeVisible();
|
||||
// 1.3.0: every admin section has its own address, down the side; Backups is one.
|
||||
await page.getByRole("navigation", { name: "Admin" }).getByRole("link", { name: "Backups" }).click();
|
||||
await expect(page.getByRole("heading", { name: "Database backups" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Back up now" })).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.1.0",
|
||||
"version": "1.9.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import React, { useCallback, useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react";
|
||||
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { ACCOUNT_NAV, AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
|
||||
import { Card, Heading } from "@/components/Panel";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
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 };
|
||||
@@ -20,40 +25,128 @@ 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" }) : "—");
|
||||
|
||||
/** The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. */
|
||||
export function Account() {
|
||||
export type AccountSection = "overview" | "details" | "security" | "privacy" | "activity";
|
||||
|
||||
const SECTIONS: Record<AccountSection, { path: string; title: string; sub: (church: string) => string }> = {
|
||||
overview: { path: "/account", title: "Your account", sub: (c) => `One account for all of ${c}'s sites and apps.` },
|
||||
details: { path: "/account/details", title: "Your details", sub: (c) => `Your name and contact details, shared with ${c}'s sites when you sign in.` },
|
||||
security: { path: "/account/security", title: "Signing in", sub: () => "Your password, two-step sign-in and recovery codes." },
|
||||
privacy: { path: "/account/privacy", title: "Privacy", sub: () => "Your news choices, a copy of your data, and deleting your account." },
|
||||
activity: { path: "/account/activity", title: "Activity", sub: () => "Recent sign-ins and changes to your account." },
|
||||
};
|
||||
|
||||
/**
|
||||
* The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. 1.3.0: in
|
||||
* sections down the side (as Cross Events' dashboard), with quick links to the church's sites.
|
||||
*/
|
||||
export function Account({ section = "overview" }: { section?: AccountSection }) {
|
||||
const branding = useBranding();
|
||||
const [me, setMe] = useState<Me | null>(null);
|
||||
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
|
||||
const s = SECTIONS[section] ?? SECTIONS.overview;
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<Me>("GET", "/me");
|
||||
if (r.status === 401) return window.location.assign(selfSignIn("/account"));
|
||||
if (r.status === 401) return window.location.assign(selfSignIn(s.path));
|
||||
if (r.ok) setMe(r.data);
|
||||
}, []);
|
||||
}, [s.path]);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
|
||||
const done = (text: string) => { setMsg({ tone: "success", text }); void load(); };
|
||||
const fail = (text: string) => setMsg({ tone: "error", text });
|
||||
|
||||
if (!me) return <Shell branding={branding}><p className="text-gray-600">Loading…</p></Shell>;
|
||||
if (!me) return <ShellLoading />;
|
||||
|
||||
const signOut = <a href={`/api/oidc/session/end?client_id=accounts-self&post_logout_redirect_uri=${encodeURIComponent(`${window.location.origin}/signed-out`)}`} className="text-sm text-brand underline">Sign out</a>;
|
||||
const first = me.name.split(" ")[0] || me.name;
|
||||
return (
|
||||
<Shell branding={branding} wide aside={<div className="flex gap-4">{me.role === "admin" && <a href="/admin" className="text-sm text-brand underline">Admin</a>}{signOut}</div>}>
|
||||
<h1 className="mb-1 text-2xl font-semibold">Your account</h1>
|
||||
<p className="mb-6 text-sm text-gray-600">One account for all of {branding.name}'s sites and apps.</p>
|
||||
<AppShell me={me} active={s.path}>
|
||||
<PageTitle icon={section === "overview" ? undefined : ACCOUNT_NAV.find((n) => n.href === s.path)?.icon} sub={s.sub(branding.name)}>{section === "overview" ? `Hi, ${first}` : s.title}</PageTitle>
|
||||
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<Profile me={me} onDone={done} onFail={fail} />
|
||||
<Security me={me} onDone={done} onFail={fail} />
|
||||
<Privacy me={me} onDone={done} onFail={fail} />
|
||||
<Activity onDone={done} />
|
||||
{section === "overview" && <Overview me={me} />}
|
||||
{section === "details" && <div className="max-w-2xl"><Profile me={me} onDone={done} onFail={fail} /></div>}
|
||||
{section === "security" && <div className="max-w-2xl"><Security me={me} onDone={done} onFail={fail} /></div>}
|
||||
{section === "privacy" && <div className="max-w-2xl"><Privacy me={me} onDone={done} onFail={fail} /></div>}
|
||||
{section === "activity" && <div className="max-w-2xl"><Activity onDone={done} /></div>}
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Overview: the church's sites, and how the account stands ────────────────
|
||||
|
||||
type App = { id: string; product: string; name: string; description: string | null; url: string };
|
||||
const APP_ICONS: Record<string, LucideIcon> = { events: Calendar, website: Globe, app: Smartphone };
|
||||
|
||||
function Overview({ me }: { me: Me }) {
|
||||
const branding = useBranding();
|
||||
const [apps, setApps] = useState<App[] | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<{ items: App[] }>("GET", "/me/apps").then((r) => { if (alive) setApps(r.ok ? r.data.items : []); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const checks: { ok: boolean; label: string; detail: string; href: string; icon: LucideIcon }[] = [
|
||||
{ ok: !!me.twoFactor, label: me.twoFactor ? "Two-step sign-in is on" : "Two-step sign-in is off", detail: me.twoFactor ? `With ${METHOD[me.twoFactor]}${me.recoveryCodesLeft < 3 ? `, ${me.recoveryCodesLeft} recovery codes left` : ""}` : "Turn it on so a password alone can't open your account", href: "/account/security", icon: me.twoFactor ? ShieldCheck : ShieldAlert },
|
||||
{ ok: me.emailVerified, label: me.emailVerified ? "Email address confirmed" : "Email address not confirmed", detail: me.email, href: "/account/details", icon: Mail },
|
||||
{ ok: true, label: "Last sign-in", detail: when(me.lastSignInAt), href: "/account/activity", icon: ActivityIcon },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<section aria-labelledby="apps-title">
|
||||
<h2 id="apps-title" className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Go to</h2>
|
||||
{apps === null && <p className="text-sm text-gray-500" role="status">Loading…</p>}
|
||||
{apps && !apps.length && (
|
||||
<Card><p className="text-sm text-gray-600">{branding.name}'s sites and apps will show here once they sign people in with this account.</p></Card>
|
||||
)}
|
||||
{apps && apps.length > 0 && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{apps.map((a) => {
|
||||
const Icon = APP_ICONS[a.product] ?? Globe;
|
||||
return (
|
||||
<a key={a.id} href={a.url} className="group flex items-center gap-4 rounded-xl border bg-white p-5 shadow-sm transition hover:border-brand/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/50">
|
||||
<span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-brand text-white" aria-hidden><Icon className="h-6 w-6" /></span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-semibold text-gray-900">{a.name}</span>
|
||||
{a.description && <span className="block text-sm text-gray-500">{a.description}</span>}
|
||||
<span className="block truncate text-xs text-gray-400">{a.url.replace(/^https?:\/\//, "").replace(/\/.*$/, "")}</span>
|
||||
</span>
|
||||
<ArrowUpRight className="h-5 w-5 shrink-0 text-gray-300 transition group-hover:text-brand" aria-hidden />
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="status-title">
|
||||
<h2 id="status-title" className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Your account</h2>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{checks.map((c) => {
|
||||
const Icon = c.icon;
|
||||
return (
|
||||
<a key={c.label} href={c.href} className="flex items-start gap-3 rounded-xl border bg-white p-4 shadow-sm hover:bg-gray-50">
|
||||
<span className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${c.ok ? "bg-brand/10 text-brand" : "bg-amber-50 text-amber-700"}`} aria-hidden><Icon className="h-4 w-4" /></span>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-sm font-medium text-gray-900">{c.label}</span>
|
||||
<span className="block truncate text-xs text-gray-500">{c.detail}</span>
|
||||
</span>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="flex flex-wrap gap-3 text-sm">
|
||||
<Link href="/account/details" className="inline-flex items-center gap-1.5 rounded-lg border bg-white px-3 py-2 text-gray-700 hover:bg-gray-50"><User className="h-4 w-4" aria-hidden /> Change your details</Link>
|
||||
<Link href="/account/privacy" className="inline-flex items-center gap-1.5 rounded-lg border bg-white px-3 py-2 text-gray-700 hover:bg-gray-50"><Lock className="h-4 w-4" aria-hidden /> Download your data</Link>
|
||||
{me.noticeVersionAccepted >= me.noticeVersion && <span className="inline-flex items-center gap-1.5 px-1 py-2 text-gray-500"><CheckCircle2 className="h-4 w-4 text-green-600" aria-hidden /> You've read the latest <a href="/privacy" className="text-brand underline">privacy notice</a></span>}
|
||||
</div>
|
||||
</Shell>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -64,7 +157,7 @@ function Profile({ me, onDone, onFail }: Props) {
|
||||
const [changingEmail, setChangingEmail] = useState(false);
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Your details</Heading>
|
||||
<Heading icon={<User className="h-4 w-4" />} sub="Change them here and the church's sites get them too.">Your details</Heading>
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
@@ -111,7 +204,7 @@ function Security({ me, onDone, onFail }: Props) {
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Signing in</Heading>
|
||||
<Heading icon={<ShieldCheck className="h-4 w-4" />}>Signing in</Heading>
|
||||
<p className="mb-3 text-sm text-gray-700">
|
||||
Two-step sign-in: {me.twoFactor ? <strong>on, with {METHOD[me.twoFactor]}</strong> : <strong>off</strong>}
|
||||
{me.twoFactor && <span className="text-gray-500"> · {me.recoveryCodesLeft} recovery codes left</span>}
|
||||
@@ -193,15 +286,24 @@ function Privacy({ me, onDone, onFail }: Props) {
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Privacy</Heading>
|
||||
<Heading icon={<Lock className="h-4 w-4" />}>Privacy</Heading>
|
||||
<form onChange={async (e) => {
|
||||
const f = new FormData(e.currentTarget);
|
||||
const r = await call("PUT", "/me/news", { email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" });
|
||||
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">
|
||||
@@ -249,7 +351,7 @@ function Activity({ onDone }: { onDone: (t: string) => void }) {
|
||||
}, []);
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity</Heading>
|
||||
<Heading icon={<ActivityIcon className="h-4 w-4" />} sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity</Heading>
|
||||
<ul className="mb-4 max-h-72 space-y-2 overflow-y-auto text-sm">
|
||||
{items.map((e, i) => (
|
||||
<li key={i} className="flex justify-between gap-3 border-b pb-2 last:border-0">
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Account, type AccountSection } from "../Account";
|
||||
|
||||
const TITLES: Record<string, string> = { details: "Your details", security: "Signing in", privacy: "Privacy", activity: "Activity" };
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ section: string }> }) {
|
||||
const { section } = await params;
|
||||
return { title: TITLES[section] ?? "Your account" };
|
||||
}
|
||||
|
||||
/** One section of the account page (1.3.0): /account/details, /security, /privacy, /activity. */
|
||||
export default async function AccountSectionPage({ params }: { params: Promise<{ section: string }> }) {
|
||||
const { section } = await params;
|
||||
if (!(section in TITLES)) notFound();
|
||||
return <Account section={section as AccountSection} />;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Card, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
@@ -19,12 +21,12 @@ export function ConfirmEmail({ token }: { token: string }) {
|
||||
return () => { alive = false; };
|
||||
}, [token]);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading>Your email address</Heading>
|
||||
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
|
||||
<a href="/account" className="text-brand underline">Back to your account</a>
|
||||
<Link href="/account" className="text-brand underline">Back to your account</Link>
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,63 +1,189 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import React, { useCallback, useState } from "react";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import {
|
||||
AlertTriangle, ArrowRight, Building2, CheckCircle2, ChevronRight, DatabaseBackup, Download, Eye, FileText, KeyRound, Link2, LogIn, Mail, MessageCircle, Play,
|
||||
RefreshCw, ScrollText, Search, ShieldCheck, Timer, UserX, Users,
|
||||
} from "lucide-react";
|
||||
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
|
||||
import { ADMIN_GROUPS, ADMIN_NAV, AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell";
|
||||
import { NoticeText } from "@/components/NoticeText";
|
||||
import { Card, Heading } from "@/components/Panel";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections";
|
||||
import { BrandStyle } from "./BrandStyle";
|
||||
|
||||
const TABS = [
|
||||
["people", "People"], ["deletions", "Deletion requests"], ["church", "Church profile"], ["linked", "Linked products"],
|
||||
["signin", "Sign-in settings"], ["messages", "Email and WhatsApp"], ["notice", "Privacy notice"], ["licence", "Licence"], ["audit", "Audit log"],
|
||||
] as const;
|
||||
type Tab = (typeof TABS)[number][0];
|
||||
|
||||
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
|
||||
type Flash = (tone: "success" | "error", text: string) => void;
|
||||
|
||||
/** Accounts' admin (docs/ACCOUNTS-1.0-PLAN.md §8). Admins only, signed in with their second step. */
|
||||
export function Admin() {
|
||||
const branding = useBranding();
|
||||
const [tab, setTab] = useState<Tab>("people");
|
||||
/**
|
||||
* Accounts' admin (docs/ACCOUNTS-1.0-PLAN.md §8). Admins only, signed in with their second step.
|
||||
* 1.3.0: one section per address, down the side (as Cross Events' settings), and Backups.
|
||||
*/
|
||||
export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
const s = ADMIN_SECTIONS[section] ?? ADMIN_SECTIONS.people;
|
||||
const [me, setMe] = useState<ShellUser | null>(null);
|
||||
const [allowed, setAllowed] = useState<boolean | null>(null);
|
||||
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
|
||||
const [waiting, setWaiting] = useState(0);
|
||||
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call("GET", "/admin/licence").then((r) => {
|
||||
Promise.all([call<ShellUser>("GET", "/me"), call("GET", "/admin/licence")]).then(([who, r]) => {
|
||||
if (!alive) return;
|
||||
if (r.status === 401) return window.location.assign(selfSignIn("/admin"));
|
||||
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn("/admin", "&acr=mfa"));
|
||||
if (who.status === 401 || r.status === 401) return window.location.assign(selfSignIn(s.path));
|
||||
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa"));
|
||||
if (who.ok) setMe(who.data);
|
||||
setAllowed(r.ok);
|
||||
// The count beside Deletion requests.
|
||||
if (r.ok) void call<{ items: Deletion[] }>("GET", "/admin/deletions").then((d) => { if (alive && d.ok) setWaiting(d.data.items.filter((x) => x.status === "waiting_approval").length); });
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [s.path]);
|
||||
|
||||
const flash: Flash = (tone, text) => setMsg({ tone, text });
|
||||
const icon = ADMIN_NAV.find((n) => n.href === s.path)?.icon;
|
||||
const badges = { "/admin/deletions": waiting };
|
||||
if (allowed === null || !me) return <ShellLoading />;
|
||||
if (!allowed) {
|
||||
return (
|
||||
<AppShell me={me} active={s.path}>
|
||||
<div className="max-w-xl"><Card><Notice tone="error">Only Accounts admins can open this page.</Notice><Link href="/account" className="text-brand underline">Your account</Link></Card></div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell me={me} active={s.path} badges={badges}>
|
||||
<PageTitle icon={section === "overview" ? undefined : icon} sub={section === "overview" ? `Welcome back, ${me.name.split(" ")[0] || me.name}. ${s.sub}` : s.sub}>{s.title}</PageTitle>
|
||||
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
||||
{section === "overview" && <Overview />}
|
||||
{section === "people" && <People flash={flash} />}
|
||||
<div className="max-w-3xl space-y-6">
|
||||
{section === "deletions" && <Deletions flash={flash} onChange={setWaiting} />}
|
||||
{section === "church" && <><Church flash={flash} /><BrandStyle flash={flash} /></>}
|
||||
{section === "linked" && <Linked flash={flash} />}
|
||||
{section === "signin" && <Settings flash={flash} title="Signing in" icon={<LogIn className="h-4 w-4" />} sub="For everyone with an account at the church." keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
|
||||
{section === "messages" && <>
|
||||
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
|
||||
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
|
||||
<WhatsAppReplies />
|
||||
</>}
|
||||
{section === "notice" && <NoticeTab flash={flash} />}
|
||||
{section === "backups" && <Backups flash={flash} />}
|
||||
{section === "jobs" && <Jobs flash={flash} />}
|
||||
{section === "licence" && <Licence flash={flash} />}
|
||||
{section === "audit" && <Audit />}
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Overview (1.8.0, as Cross Events' admin dashboard) ─────────────────────
|
||||
|
||||
type Linked = { hubConnected: boolean; items: { installId: string; name: string; listed: boolean; signsInHere: boolean }[] };
|
||||
type OverviewData = { people: number | null; deletions: number | null; linked: Linked | null; licence: { connected: boolean; state: string } | null; backups: BackupList | null };
|
||||
|
||||
const TILE: Record<string, string> = Object.fromEntries(Object.values(ADMIN_SECTIONS).map((x) => [x.path, x.tile]));
|
||||
|
||||
function Stat({ icon, label, value, detail, href, warn }: { icon: React.ReactNode; label: string; value: React.ReactNode; detail?: React.ReactNode; href: string; warn?: boolean }) {
|
||||
return (
|
||||
<Link href={href} className="group rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg ${warn ? "bg-amber-50 text-amber-700" : "bg-brand/10 text-brand"}`} aria-hidden>{icon}</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-xs text-gray-500">{label}</span>
|
||||
<span className="block truncate text-xl font-semibold text-gray-900">{value}</span>
|
||||
</span>
|
||||
</div>
|
||||
{detail && <p className="mt-2 text-xs text-gray-500">{detail}</p>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function Overview() {
|
||||
const [d, setD] = useState<OverviewData | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
Promise.all([
|
||||
call<{ total: number }>("GET", "/admin/people?q="), call<{ items: Deletion[] }>("GET", "/admin/deletions"), call<Linked>("GET", "/admin/linked-products"),
|
||||
call<{ connected: boolean; state: string }>("GET", "/admin/licence"), call<BackupList>("GET", "/admin/backups"),
|
||||
]).then(([people, dels, linked, licence, backups]) => {
|
||||
if (!alive) return;
|
||||
setD({
|
||||
people: people.ok ? people.data.total : null,
|
||||
deletions: dels.ok ? dels.data.items.filter((x) => x.status === "waiting_approval").length : null,
|
||||
linked: linked.ok ? linked.data : null,
|
||||
licence: licence.ok ? licence.data : null,
|
||||
backups: backups.ok ? backups.data : null,
|
||||
});
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!d) return <p className="text-sm text-gray-500" role="status">Loading…</p>;
|
||||
|
||||
const flash: Flash = (tone, text) => setMsg({ tone, text });
|
||||
if (allowed === null) return <Shell branding={branding} wide><p className="text-gray-600">Loading…</p></Shell>;
|
||||
if (!allowed) return <Shell branding={branding}><Card><Notice tone="error">Only Accounts admins can open this page.</Notice><a href="/account" className="text-brand underline">Your account</a></Card></Shell>;
|
||||
const connected = d.linked?.items.filter((l) => l.signsInHere).length ?? 0;
|
||||
const notConnected = d.linked?.items.filter((l) => !l.signsInHere && l.listed) ?? [];
|
||||
const lastBackup = d.backups?.items[0]?.createdAt ?? null;
|
||||
const todo: { text: string; href: string; action: string }[] = [
|
||||
...(d.deletions ? [{ text: `${d.deletions} ${d.deletions === 1 ? "person has" : "people have"} asked to delete their account.`, href: "/admin/deletions", action: "Review" }] : []),
|
||||
...(d.licence && !d.licence.connected ? [{ text: "Accounts isn't connected to Cross Code yet, so the church's sites can't find it.", href: "/admin/licence", action: "Connect" }] : []),
|
||||
...(notConnected.length ? [{ text: `${notConnected.map((l) => l.name).join(", ")} ${notConnected.length === 1 ? "doesn't" : "don't"} sign people in here yet.`, href: "/admin/linked", action: "Connect" }] : []),
|
||||
...(d.backups?.lastError ? [{ text: "The last backup didn't work.", href: "/admin/backups", action: "See why" }] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
<Shell branding={branding} wide aside={<a href="/account" className="text-sm text-brand underline">Your account</a>}>
|
||||
<h1 className="mb-4 text-2xl font-semibold">Accounts admin</h1>
|
||||
<nav className="mb-6 flex flex-wrap gap-2" aria-label="Admin sections">
|
||||
{TABS.map(([id, label]) => (
|
||||
<button key={id} type="button" onClick={() => { setTab(id); setMsg(null); }} aria-current={tab === id ? "page" : undefined}
|
||||
className={`rounded-full px-3 py-1.5 text-sm ${tab === id ? "bg-brand text-white" : "border bg-white text-gray-700"}`}>{label}</button>
|
||||
))}
|
||||
</nav>
|
||||
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
||||
{tab === "people" && <People flash={flash} />}
|
||||
{tab === "deletions" && <Deletions flash={flash} />}
|
||||
{tab === "church" && <Church flash={flash} />}
|
||||
{tab === "linked" && <Linked flash={flash} />}
|
||||
{tab === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
|
||||
{tab === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
|
||||
{tab === "notice" && <NoticeTab flash={flash} />}
|
||||
{tab === "licence" && <Licence flash={flash} />}
|
||||
{tab === "audit" && <Audit />}
|
||||
</Shell>
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<Stat icon={<Users className="h-5 w-5" />} label="People with an account" value={d.people ?? "—"} href="/admin/people" detail="Find someone" />
|
||||
<Stat icon={<UserX className="h-5 w-5" />} label="Deletion requests waiting" value={d.deletions ?? "—"} warn={!!d.deletions} href="/admin/deletions" detail={d.deletions ? "They need your answer" : "None waiting"} />
|
||||
<Stat icon={<Link2 className="h-5 w-5" />} label="Sites that sign in here" value={d.linked ? `${connected} of ${d.linked.items.length}` : "—"} warn={notConnected.length > 0} href="/admin/linked" detail={d.linked && !d.linked.hubConnected ? "Not connected to the Hub" : "Linked products"} />
|
||||
<Stat icon={<DatabaseBackup className="h-5 w-5" />} label="Last backup" value={lastBackup ? when(lastBackup) : "None yet"} warn={!!d.backups?.lastError} href="/admin/backups" detail={d.backups ? (d.backups.nightly ? "Every night at 02:00" : "Nightly backups are off") : undefined} />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<Heading icon={todo.length ? <AlertTriangle className="h-4 w-4" /> : <CheckCircle2 className="h-4 w-4" />}>{todo.length ? "Needs you" : "Nothing needs you right now"}</Heading>
|
||||
{todo.length > 0 ? (
|
||||
<ul className="divide-y">
|
||||
{todo.map((t) => (
|
||||
<li key={t.href} className="flex flex-wrap items-center justify-between gap-3 py-3">
|
||||
<span className="text-sm text-gray-700">{t.text}</span>
|
||||
<Link href={t.href} className="inline-flex items-center gap-1 rounded-lg bg-brand px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-dark">{t.action}<ArrowRight className="h-3.5 w-3.5" aria-hidden /></Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : <p className="text-sm text-gray-600">Nothing is waiting for an admin. Anything that is (a deletion request, a site to connect, a backup that failed) shows here.</p>}
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<Heading sub="Every setting, one click away.">All settings</Heading>
|
||||
<div className="space-y-5">
|
||||
{ADMIN_GROUPS.filter((g) => g.title).map((g) => (
|
||||
<div key={g.title}>
|
||||
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{g.title}</h3>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{g.items.map((n) => {
|
||||
const Icon = n.icon;
|
||||
return (
|
||||
<Link key={n.href} href={n.href} className="flex items-start gap-3 rounded-xl border bg-white p-4 shadow-sm transition hover:border-brand/40 hover:shadow">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand" aria-hidden><Icon className="h-5 w-5" /></span>
|
||||
<span className="min-w-0">
|
||||
<span className="block text-sm font-semibold text-gray-900">{n.label}</span>
|
||||
<span className="mt-0.5 block text-xs text-gray-500">{TILE[n.href]}</span>
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -66,6 +192,9 @@ export function Admin() {
|
||||
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
|
||||
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
|
||||
|
||||
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((x) => x[0]!.toUpperCase()).join("") || "?";
|
||||
const chip = "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium";
|
||||
|
||||
function People({ flash }: { flash: Flash }) {
|
||||
const [q, setQ] = useState("");
|
||||
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
|
||||
@@ -85,28 +214,47 @@ function People({ flash }: { flash: Flash }) {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<Card>
|
||||
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
|
||||
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
|
||||
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-3 flex gap-2">
|
||||
<span className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" aria-hidden />
|
||||
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="w-full rounded-lg border py-2 pl-9 pr-3" />
|
||||
</span>
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
|
||||
<ul className="divide-y">
|
||||
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} {list?.total === 1 ? "person" : "people"}</p>
|
||||
<ul className="-mx-2 divide-y">
|
||||
{list?.items.map((p) => (
|
||||
<li key={p.id}>
|
||||
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
|
||||
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
|
||||
<span className="block text-sm text-gray-500">{p.email}</span>
|
||||
<button type="button" onClick={() => show(p.id)} aria-current={open?.id === p.id ? "true" : undefined}
|
||||
className={`flex w-full items-center gap-3 rounded-lg px-2 py-2.5 text-left hover:bg-gray-50 ${open?.id === p.id ? "bg-brand/5" : ""}`}>
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand-dark" aria-hidden>{initials(p.name)}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex flex-wrap items-center gap-1.5 font-medium text-gray-900">
|
||||
{p.name}
|
||||
{p.role === "admin" && <span className={`${chip} bg-brand/10 text-brand-dark`}>admin</span>}
|
||||
{p.status !== "active" && <span className={`${chip} bg-amber-50 text-amber-800`}>{p.status}</span>}
|
||||
</span>
|
||||
<span className="block truncate text-sm text-gray-500">{p.email}</span>
|
||||
</span>
|
||||
<span className="hidden shrink-0 text-right text-xs text-gray-500 sm:block">{p.twoFactor ? <span className="inline-flex items-center gap-1 text-green-700"><ShieldCheck className="h-3.5 w-3.5" aria-hidden />Two-step</span> : null}<span className="block">{p.lastSignInAt ? `Signed in ${when(p.lastSignInAt)}` : "Never signed in"}</span></span>
|
||||
<ChevronRight className="h-4 w-4 shrink-0 text-gray-300" aria-hidden />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
{open && (
|
||||
<Card>
|
||||
<Heading sub={open.email}>{open.name}</Heading>
|
||||
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
|
||||
{open ? (
|
||||
<Card className="lg:sticky lg:top-20">
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-brand/10 text-sm font-semibold text-brand-dark" aria-hidden>{initials(open.name)}</span>
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-lg font-semibold text-gray-900">{open.name}</h2>
|
||||
<p className="truncate text-xs text-gray-500">{open.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="mb-4 grid grid-cols-2 gap-y-1.5 rounded-lg bg-gray-50 p-3 text-sm">
|
||||
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
|
||||
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
|
||||
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
|
||||
@@ -117,12 +265,18 @@ function People({ flash }: { flash: Flash }) {
|
||||
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
|
||||
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
|
||||
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
|
||||
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
|
||||
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => { if (open.status === "active" && !window.confirm(`Deactivate ${open.name}? They're signed out of every site straight away.`)) return; void act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated."); }}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
|
||||
</div>
|
||||
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
|
||||
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
|
||||
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
|
||||
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((x, i) => <li key={i}>{x.type} · {when(x.at)} {x.ip && <span className="text-gray-500">· {x.ip}</span>}</li>)}</ul>
|
||||
{!open.signIns.length && <p className="text-sm text-gray-500">None yet.</p>}
|
||||
</Card>
|
||||
) : (
|
||||
<div className="hidden rounded-xl border border-dashed p-8 text-center text-sm text-gray-500 lg:block">
|
||||
<Users className="mx-auto mb-2 h-6 w-6 text-gray-300" aria-hidden />
|
||||
Choose someone to see their account and what you can do for them.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -132,16 +286,16 @@ function People({ flash }: { flash: Flash }) {
|
||||
|
||||
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
|
||||
|
||||
function Deletions({ flash }: { flash: Flash }) {
|
||||
function Deletions({ flash, onChange }: { flash: Flash; onChange: (waiting: number) => void }) {
|
||||
const [items, setItems] = useState<Deletion[]>([]);
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
|
||||
if (r.ok) setItems(r.data.items);
|
||||
}, []);
|
||||
if (r.ok) { setItems(r.data.items); onChange(r.data.items.filter((x) => x.status === "waiting_approval").length); }
|
||||
}, [onChange]);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
|
||||
<Heading icon={<UserX className="h-4 w-4" />} sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
|
||||
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
|
||||
<ul className="divide-y">
|
||||
{items.map((d) => (
|
||||
@@ -180,7 +334,8 @@ function Church({ flash }: { flash: Flash }) {
|
||||
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
|
||||
<Heading icon={<Building2 className="h-4 w-4" />} sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
|
||||
{c.branding.logoUrl && <img src={c.branding.logoUrl} alt="The church's logo" className="mb-4 h-12 w-auto rounded border bg-gray-50 p-1" />}
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
@@ -221,7 +376,7 @@ function Linked({ flash }: { flash: Flash }) {
|
||||
if (!data) return <p className="text-gray-600">Loading…</p>;
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
|
||||
<Heading icon={<Link2 className="h-4 w-4" />} sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
|
||||
{!data.hubConnected && <Notice tone="warning">Accounts isn't connected to the Hub yet (Licence).</Notice>}
|
||||
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
|
||||
<ul className="divide-y">
|
||||
@@ -244,13 +399,14 @@ function Linked({ flash }: { flash: Flash }) {
|
||||
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
|
||||
signup_enabled: ["Members can create their own account", "bool"],
|
||||
two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"],
|
||||
signin_notices: ["Tell people by email (and WhatsApp) each time they sign in", "bool"],
|
||||
session_days: ['Days "Keep me signed in" lasts', "number"],
|
||||
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
|
||||
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
|
||||
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
|
||||
};
|
||||
|
||||
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: string[]; title: string; icon: React.ReactNode; sub?: string }) {
|
||||
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
@@ -258,9 +414,10 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!values) return <p className="text-gray-600">Loading…</p>;
|
||||
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
|
||||
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true, signin_notices: true };
|
||||
return (
|
||||
<Card>
|
||||
<Heading icon={icon} sub={sub}>{title}</Heading>
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
@@ -271,7 +428,7 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
else body[k] = String(f.get(k) ?? "");
|
||||
}
|
||||
const r = await call("PUT", "/admin/settings", body);
|
||||
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message);
|
||||
if (r.ok) flash("success", `${title}: saved.`); else flash("error", r.error.message);
|
||||
}}>
|
||||
{keys.map((k) => {
|
||||
const [label, kind] = SETTING_LABELS[k]!;
|
||||
@@ -283,41 +440,83 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit">Save</Button>
|
||||
{keys.includes("smtp_host") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-email"); flash(r.ok ? "success" : "error", r.ok ? "A test email is on its way to you." : r.error.message); }}>Send a test email</Button>}
|
||||
{keys.includes("wawp_instance_id") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-whatsapp"); flash(r.ok ? "success" : "error", r.ok ? "A test WhatsApp message is on its way to your phone." : r.error.message); }}>Send a test WhatsApp</Button>}
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
|
||||
|
||||
function NoticeTab({ flash }: { flash: Flash }) {
|
||||
const [current, setCurrent] = useState<{ version: number; title: string; body: string } | null>(null);
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<{ current: { version: number; title: string; body: string } }>("GET", "/admin/notices");
|
||||
if (r.ok) setCurrent(r.data.current);
|
||||
/** 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; };
|
||||
}, []);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
if (!current) return <p className="text-gray-600">Loading…</p>;
|
||||
if (!data) return null;
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub={`Version ${current.version}. Publishing a new version asks everyone to read it the next time they sign in.`}>Privacy notice</Heading>
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
if (!window.confirm("Publish this as a new version? Everyone will be asked to read it when they next sign in.")) return;
|
||||
const f = new FormData(e.currentTarget);
|
||||
const r = await call("POST", "/admin/notices", { title: f.get("title"), body: f.get("body") });
|
||||
if (r.ok) { flash("success", "Published."); void load(); } else flash("error", r.error.message);
|
||||
}}>
|
||||
<Field label="Title" name="title" defaultValue={current.title} required />
|
||||
<label htmlFor="notice-body" className="mb-1 block text-sm font-medium">Text</label>
|
||||
<textarea id="notice-body" name="body" defaultValue={current.body} rows={14} className="mb-4 w-full rounded-lg border p-3 text-sm" required />
|
||||
<Button type="submit">Publish a new version</Button>
|
||||
</form>
|
||||
<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 };
|
||||
|
||||
function NoticeTab({ flash }: { flash: Flash }) {
|
||||
const [data, setData] = useState<{ current: NoticeVersion; builtIn: NoticeVersion | null } | null>(null);
|
||||
const [draft, setDraft] = useState<{ title: string; body: string } | null>(null);
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<{ current: NoticeVersion; builtIn?: NoticeVersion }>("GET", "/admin/notices");
|
||||
if (r.ok) { setData({ current: r.data.current, builtIn: r.data.builtIn ?? null }); setDraft({ title: r.data.current.title, body: r.data.current.body }); }
|
||||
}, []);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
if (!data || !draft) return <p className="text-gray-600">Loading…</p>;
|
||||
const { current, builtIn } = data;
|
||||
const isBuiltIn = current.version === 1;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<Heading icon={<FileText className="h-4 w-4" />} sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
|
||||
{builtIn && !isBuiltIn && (
|
||||
<p className="mb-4 text-sm text-gray-600">
|
||||
The built-in notice was rewritten in Accounts 1.3.0 to say more fully what Accounts does.{" "}
|
||||
<Button type="button" variant="link" className="text-sm" onClick={() => setDraft({ title: builtIn.title, body: builtIn.body })}>Start from the built-in notice</Button>
|
||||
</p>
|
||||
)}
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
if (!window.confirm("Publish this as a new version? Everyone will be asked to read it when they next sign in.")) return;
|
||||
const r = await call("POST", "/admin/notices", draft);
|
||||
if (r.ok) { flash("success", "Published."); void load(); } else flash("error", r.error.message);
|
||||
}}>
|
||||
<Field label="Title" name="title" value={draft.title} onChange={(e) => setDraft({ ...draft, title: e.target.value })} required />
|
||||
<label htmlFor="notice-body" className="mb-1 block text-sm font-medium">Text</label>
|
||||
<textarea id="notice-body" name="body" value={draft.body} onChange={(e) => setDraft({ ...draft, body: e.target.value })} rows={18} className="mb-1 w-full rounded-lg border p-3 font-mono text-xs" required />
|
||||
<p className="mb-4 text-xs text-gray-500">A line starting with "## " is a heading, and one starting with "• " is a bullet.</p>
|
||||
<Button type="submit">Publish a new version</Button>
|
||||
</form>
|
||||
</Card>
|
||||
<Card>
|
||||
<Heading icon={<Eye className="h-4 w-4" />} sub="As people will see it.">Preview</Heading>
|
||||
<h3 className="mb-3 text-base font-semibold text-gray-900">{draft.title}</h3>
|
||||
<div className="max-h-[32rem] overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={draft.body} compact /></div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Licence({ flash }: { flash: Flash }) {
|
||||
const [s, setS] = useState<{ connected: boolean; state: string; customer: string | null; endsAt: string | null; lastHeartbeatAt: string | null; lastError: string | null } | null>(null);
|
||||
const load = useCallback(async () => {
|
||||
@@ -328,7 +527,7 @@ function Licence({ flash }: { flash: Flash }) {
|
||||
if (!s) return <p className="text-gray-600">Loading…</p>;
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
|
||||
<Heading icon={<KeyRound className="h-4 w-4" />} sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
|
||||
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
|
||||
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
|
||||
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
|
||||
@@ -359,7 +558,7 @@ function Audit() {
|
||||
}, []);
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Audit log</Heading>
|
||||
<Heading icon={<ScrollText className="h-4 w-4" />}>Audit log</Heading>
|
||||
<ul className="divide-y text-sm">
|
||||
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
|
||||
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
|
||||
@@ -367,3 +566,232 @@ function Audit() {
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Backups (1.3.0) ─────────────────────────────────────────────────────────
|
||||
|
||||
type BackupList = { items: { filename: string; size: number; createdAt: string }[]; nightly: boolean; retain: number; lastError: string | null };
|
||||
|
||||
const size = (n: number) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / (1024 * 1024)).toFixed(1)} MB`);
|
||||
|
||||
function Backups({ flash }: { flash: Flash }) {
|
||||
const [data, setData] = useState<BackupList | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<BackupList>("GET", "/admin/backups");
|
||||
if (r.ok) setData(r.data);
|
||||
}, []);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
if (!data) return <p className="text-gray-600">Loading…</p>;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<Heading icon={<DatabaseBackup className="h-4 w-4" />} sub="Every night at 02:00, and before every update of Accounts. Kept on this server only, never sent anywhere.">Database backups</Heading>
|
||||
{data.lastError && <Notice tone="warning">The last backup didn't work: {data.lastError}</Notice>}
|
||||
<Button busy={running} onClick={async () => {
|
||||
setRunning(true);
|
||||
const r = await call<{ filename: string }>("POST", "/admin/backups/run");
|
||||
setRunning(false);
|
||||
if (r.ok) { flash("success", `Backup made: ${r.data.filename}`); } else flash("error", r.error.message);
|
||||
void load();
|
||||
}}>Back up now</Button>
|
||||
|
||||
<form className="mt-5 flex flex-wrap items-end gap-x-4 gap-y-2 border-t pt-4" onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
setSaving(true);
|
||||
const r = await call<{ deleted: number }>("PUT", "/admin/backups/settings", { retain: Number(f.get("retain")), nightly: f.get("nightly") === "on" });
|
||||
setSaving(false);
|
||||
if (r.ok) { flash("success", r.data.deleted ? `Saved. ${r.data.deleted} older backups were deleted.` : "Saved."); void load(); } else flash("error", r.error.message);
|
||||
}}>
|
||||
<div className="w-full"><Checkbox name="nightly" label="Back up every night" defaultChecked={data.nightly} hint="Backups before each update are made either way." /></div>
|
||||
<Field label="Keep the newest" name="retain" type="number" min={1} max={365} defaultValue={String(data.retain)} className="mb-0 w-32" />
|
||||
<span className="pb-3 text-sm text-gray-500">backups, and delete older ones</span>
|
||||
<Button type="submit" variant="secondary" busy={saving} className="mb-1 ml-auto">Save</Button>
|
||||
</form>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<Heading sub="A backup holds everyone's details: keep a downloaded copy somewhere safe, and delete it when you're done.">Backups on this server</Heading>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="min-w-full text-sm">
|
||||
<thead><tr className="border-b bg-gray-50 text-left text-gray-600"><th className="p-2.5 font-medium">Made</th><th className="p-2.5 font-medium">Size</th><th className="p-2.5 font-medium"><span className="sr-only">Download</span></th></tr></thead>
|
||||
<tbody>
|
||||
{data.items.map((b) => (
|
||||
<tr key={b.filename} className="border-t">
|
||||
<td className="p-2.5">{when(b.createdAt)}</td>
|
||||
<td className="p-2.5 text-gray-500">{size(b.size)}</td>
|
||||
<td className="p-2.5 text-right">
|
||||
<a href={`/api/v2/admin/backups/${encodeURIComponent(b.filename)}/download`} download className="inline-flex items-center gap-1.5 text-brand hover:underline">
|
||||
<Download className="h-3.5 w-3.5" aria-hidden /> Download
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!data.items.length && <tr><td colSpan={3} className="p-3 text-gray-500">No backups yet.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Background jobs (1.4.0, as Cross Events) ────────────────────────────────
|
||||
|
||||
type JobRun = { state: string; createdOn?: string | null; startedOn: string | null; completedOn: string | null; output: unknown };
|
||||
type JobInfo = {
|
||||
name: string; label: string; cron: string; enabled: boolean; envFlag: string | null; nextRun: string | null; recent: JobRun[];
|
||||
envEnabled: boolean; envCron: string; defaultCron: string; override: { enabled: boolean | null; cron: string | null };
|
||||
};
|
||||
type JobList = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
|
||||
|
||||
const RUN_STATE: Record<string, string> = {
|
||||
completed: "bg-green-50 text-green-800", failed: "bg-red-50 text-red-700", active: "bg-blue-50 text-blue-700",
|
||||
created: "bg-gray-100 text-gray-600", retry: "bg-amber-50 text-amber-800", cancelled: "bg-gray-100 text-gray-500",
|
||||
};
|
||||
const SCHEDULES = [
|
||||
{ label: "Every minute", cron: "* * * * *" }, { label: "Every 5 minutes", cron: "*/5 * * * *" }, { label: "Every 15 minutes", cron: "*/15 * * * *" },
|
||||
{ label: "Every hour", cron: "0 * * * *" }, { label: "Daily at 02:00", cron: "0 2 * * *" }, { label: "Daily at 07:00", cron: "0 7 * * *" },
|
||||
];
|
||||
|
||||
function describeCron(cron: string): string {
|
||||
if (cron === "* * * * *") return "Every minute";
|
||||
const m = /^\*\/(\d+) \* \* \* \*$/.exec(cron);
|
||||
if (m) return `Every ${m[1]} minutes`;
|
||||
const h = /^(\d+) \* \* \* \*$/.exec(cron);
|
||||
if (h) return `Every hour at :${h[1]!.padStart(2, "0")}`;
|
||||
const d = /^(\d+) (\d+) \* \* \*$/.exec(cron);
|
||||
if (d) return `Daily at ${d[2]!.padStart(2, "0")}:${d[1]!.padStart(2, "0")}`;
|
||||
return cron;
|
||||
}
|
||||
|
||||
function runText(r: JobRun): string {
|
||||
if (r.output === null || r.output === undefined) return "";
|
||||
if (r.state === "failed" && typeof r.output === "object" && r.output && "message" in r.output) return String((r.output as { message: unknown }).message);
|
||||
try { return JSON.stringify(r.output); } catch { return ""; }
|
||||
}
|
||||
|
||||
/** An on/off switch (role="switch", so screen readers hear on and off). */
|
||||
function Toggle({ on, label, disabled, onChange }: { on: boolean; label: string; disabled?: boolean; onChange: (on: boolean) => void }) {
|
||||
return (
|
||||
<button type="button" role="switch" aria-checked={on} aria-label={label} disabled={disabled} onClick={() => onChange(!on)}
|
||||
className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${on ? "bg-brand" : "bg-gray-300"}`}>
|
||||
<span className={`inline-block h-5 w-5 rounded-full bg-white shadow transition-transform ${on ? "translate-x-5" : "translate-x-0.5"}`} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function Jobs({ flash }: { flash: Flash }) {
|
||||
const [data, setData] = useState<JobList | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
// Not tied to `flash` (a new function each render): the list loads once, then on Refresh.
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<JobList>("GET", "/admin/jobs");
|
||||
if (r.ok) { setData(r.data); setLoadError(null); } else setLoadError(r.error.message);
|
||||
}, []);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
|
||||
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
|
||||
setBusy(job.name);
|
||||
const r = await call("PUT", `/admin/jobs/${encodeURIComponent(job.name)}`, change);
|
||||
setBusy(null);
|
||||
if (r.ok) { flash("success", done); setEditing(null); void load(); } else flash("error", r.error.message);
|
||||
};
|
||||
const runNow = async (job: JobInfo) => {
|
||||
setBusy(job.name);
|
||||
const r = await call<{ queued: boolean }>("POST", `/admin/jobs/${encodeURIComponent(job.name)}/run`);
|
||||
setBusy(null);
|
||||
if (r.ok) {
|
||||
flash("success", r.data.queued ? `"${job.label}" queued: it starts within a few seconds.` : `"${job.label}" ran.`);
|
||||
setTimeout(() => void load(), r.data.queued ? 4000 : 0);
|
||||
} else flash("error", r.error.message);
|
||||
};
|
||||
|
||||
if (!data) return loadError ? <Notice tone="error">{loadError}</Notice> : <p className="text-gray-600">Loading…</p>;
|
||||
const off = data.mode === "off";
|
||||
return (
|
||||
<Card>
|
||||
<div className="mb-3 flex items-start justify-between gap-3">
|
||||
<Heading icon={<Timer className="h-4 w-4" />} sub={`Times are ${data.timezone}. Each job runs once per schedule, however many server processes there are.`}>Jobs</Heading>
|
||||
<Button variant="secondary" onClick={() => void load()}><RefreshCw className="mr-1.5 inline h-3.5 w-3.5" aria-hidden />Refresh</Button>
|
||||
</div>
|
||||
{off && <Notice tone="warning">All background jobs are switched off in the server's .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change that from the Hub.</Notice>}
|
||||
{data.mode === "timers" && <Notice tone="warning">The job queue couldn't start, so jobs run on simple timers in this process (history only since the last restart).</Notice>}
|
||||
<ul className="divide-y rounded-lg border">
|
||||
{data.jobs.map((job) => {
|
||||
const last = job.recent[0];
|
||||
const mine = busy === job.name;
|
||||
const isEditing = editing?.name === job.name;
|
||||
return (
|
||||
<li key={job.name} className="p-3">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||
<Toggle on={job.enabled} disabled={mine || off} label={`${job.label}: ${job.enabled ? "on" : "off"}`}
|
||||
onChange={(on) => void save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)} />
|
||||
<div className="mr-auto min-w-0">
|
||||
<div className={`text-sm font-medium ${job.enabled ? "text-gray-900" : "text-gray-500"}`}>{job.label}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
|
||||
{job.override.enabled !== null
|
||||
? <> · {job.enabled ? "switched on" : "switched off"} here · <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { enabled: null }, `"${job.label}" follows the .env again.`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
|
||||
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
|
||||
</div>
|
||||
</div>
|
||||
{last && (
|
||||
<button type="button" onClick={() => setOpen(open === job.name ? null : job.name)} title="Recent runs" className={`rounded px-2 py-0.5 text-xs ${RUN_STATE[last.state] ?? "bg-gray-100 text-gray-600"}`}>
|
||||
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn)}
|
||||
</button>
|
||||
)}
|
||||
<Button variant="secondary" disabled={mine || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}>Schedule</Button>
|
||||
<Button variant="secondary" disabled={!!busy || off} onClick={() => void runNow(job)}><Play className="mr-1 inline h-3.5 w-3.5" aria-hidden />Run now</Button>
|
||||
</div>
|
||||
{isEditing && editing && (
|
||||
<form className="mt-3 space-y-2 rounded-lg border bg-gray-50 p-3" onSubmit={(e) => { e.preventDefault(); void save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{SCHEDULES.map((p) => (
|
||||
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
|
||||
className={`rounded border px-2 py-1 text-xs ${editing.cron === p.cron ? "border-brand bg-white font-medium" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<Field label="Cron (minute hour day month weekday)" name="cron" value={editing.cron} maxLength={100} className="mb-0 w-64 font-mono"
|
||||
onChange={(e) => setEditing({ name: job.name, cron: e.target.value })} hint={describeCron(editing.cron.trim())} />
|
||||
<div className="ml-auto flex gap-2 pb-6">
|
||||
<Button type="button" variant="secondary" onClick={() => setEditing(null)}>Cancel</Button>
|
||||
<Button type="submit" busy={mine} disabled={!editing.cron.trim()}>Save schedule</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
The server's own schedule is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (from the .env; normally ${describeCron(job.defaultCron)})` : ""}.{" "}
|
||||
{job.override.cron !== null && <button type="button" disabled={mine} className="underline hover:text-gray-700" onClick={() => void save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}>Use that again</button>}
|
||||
</p>
|
||||
</form>
|
||||
)}
|
||||
{open === job.name && job.recent.length > 0 && (
|
||||
<div className="mt-2 overflow-x-auto">
|
||||
<table className="w-full text-xs">
|
||||
<thead className="text-gray-500"><tr><th className="py-1 text-left font-medium">Started</th><th className="text-left font-medium">Finished</th><th className="text-left font-medium">State</th><th className="text-left font-medium">Result</th></tr></thead>
|
||||
<tbody>
|
||||
{job.recent.map((r, i) => (
|
||||
<tr key={i} className="border-t">
|
||||
<td className="whitespace-nowrap py-1 pr-2">{when(r.startedOn)}</td>
|
||||
<td className="whitespace-nowrap pr-2">{when(r.completedOn)}</td>
|
||||
<td className="pr-2"><span className={`rounded px-1.5 py-0.5 ${RUN_STATE[r.state] ?? ""}`}>{r.state}</span></td>
|
||||
<td className="break-all font-mono text-[11px] text-gray-600">{runText(r)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="mt-3 text-xs text-gray-500">Without a choice here, the server's .env applies: a job's own flag (e.g. BACKUP_ENABLED=false) and JOB_SCHEDULE_<NAME>. The nightly backup also follows Backups → "Back up every night".</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { CORNERS, FONT_PAIRING_IDS, FONT_PAIRINGS, type Corners, type FontPairing } from "@crosscode/contracts";
|
||||
import { Button } from "@crosscode/ui";
|
||||
import { Card, Heading } from "@/components/Panel";
|
||||
import { call } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type Style = { fontPairing: FontPairing | null; corners: Corners | null };
|
||||
type ChurchStyle = { branding: { style?: Style } };
|
||||
|
||||
const CORNER_LABELS: Record<Corners, { name: string; radius: string }> = {
|
||||
sharp: { name: "Sharp", radius: "0" },
|
||||
soft: { name: "Soft", radius: "0.5rem" },
|
||||
round: { name: "Round", radius: "9999px" },
|
||||
};
|
||||
|
||||
/**
|
||||
* The church's brand style (1.7.0, WEBSITE-1.0-PLAN §3): a font pairing and corners, shared by
|
||||
* Accounts' pages, the Website and Cross Events. Each option is shown in its own fonts (fonts.css
|
||||
* is loaded on every page; a pairing's files download only when shown).
|
||||
*/
|
||||
export function BrandStyle({ flash }: { flash: (tone: "success" | "error", text: string) => void }) {
|
||||
const router = useRouter();
|
||||
const [saved, setSaved] = useState<Style | null>(null);
|
||||
const [style, setStyle] = useState<Style>({ fontPairing: null, corners: null });
|
||||
const [busy, setBusy] = useState(false);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<ChurchStyle>("GET", "/admin/church").then((r) => {
|
||||
if (!alive || !r.ok) return;
|
||||
const s = { fontPairing: r.data.branding.style?.fontPairing ?? null, corners: r.data.branding.style?.corners ?? null };
|
||||
setSaved(s);
|
||||
setStyle(s);
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!saved) return null;
|
||||
const changed = saved.fontPairing !== style.fontPairing || saved.corners !== style.corners;
|
||||
|
||||
const option = (selected: boolean) => `block cursor-pointer rounded-xl border p-4 transition focus-within:ring-2 focus-within:ring-brand/50 ${selected ? "border-brand bg-brand/5 ring-1 ring-brand" : "border-gray-200 hover:border-gray-300"}`;
|
||||
|
||||
return (
|
||||
<Card className="mt-6">
|
||||
<Heading sub="How the church's sites look: these sign-in pages, the website and Cross Events' public pages. Colours and logo are above.">Brand style</Heading>
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
const r = await call<ChurchStyle>("PUT", "/admin/church", { branding: { style } });
|
||||
setBusy(false);
|
||||
if (r.ok) {
|
||||
setSaved(style);
|
||||
flash("success", "Saved. The church's sites use the new style.");
|
||||
router.refresh();
|
||||
} else flash("error", r.error.message);
|
||||
}}>
|
||||
<fieldset className="mb-6">
|
||||
<legend className="mb-1 text-sm font-semibold text-gray-900">Fonts</legend>
|
||||
<p className="mb-3 text-sm text-gray-600">A font for headings and one for text. The website's template recommends three, but any works.</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className={option(style.fontPairing === null)}>
|
||||
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === null} onChange={() => setStyle({ ...style, fontPairing: null })} />
|
||||
<span className="block text-lg font-semibold [font-family:ui-sans-serif,system-ui,sans-serif]">Device fonts</span>
|
||||
<span className="mt-1 block text-sm text-gray-600 [font-family:ui-sans-serif,system-ui,sans-serif]">Each phone and computer's own. The website uses its template's fonts.</span>
|
||||
</label>
|
||||
{FONT_PAIRING_IDS.map((id) => {
|
||||
const p = FONT_PAIRINGS[id];
|
||||
return (
|
||||
<label key={id} className={option(style.fontPairing === id)} data-cc-fonts={id}>
|
||||
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === id} onChange={() => setStyle({ ...style, fontPairing: id })} />
|
||||
<span className="block text-lg font-semibold [font-family:var(--cc-font-heading)] [font-variation-settings:var(--cc-heading-variation,normal)]">{p.name}: Welcome home</span>
|
||||
<span className="mt-1 block text-sm text-gray-700 [font-family:var(--cc-font-body)]">{p.feel}. <em>Sundays at 09:00.</em></span>
|
||||
<span className="mt-2 block text-xs text-gray-500 [font-family:ui-sans-serif,system-ui,sans-serif]">{p.heading.family}{p.body.family !== p.heading.family && ` and ${p.body.family}`}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="mb-6">
|
||||
<legend className="mb-1 text-sm font-semibold text-gray-900">Corners</legend>
|
||||
<p className="mb-3 text-sm text-gray-600">Of buttons, cards, photos and fields.</p>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{CORNERS.map((id) => (
|
||||
<label key={id} className={option((style.corners ?? "soft") === id)}>
|
||||
<input type="radio" name="corners" className="sr-only" checked={(style.corners ?? "soft") === id} onChange={() => setStyle({ ...style, corners: id })} />
|
||||
<span className="mb-2 block h-8 w-full bg-brand" style={{ borderRadius: CORNER_LABELS[id].radius }} aria-hidden />
|
||||
<span className="block text-sm font-medium">{CORNER_LABELS[id].name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<Button type="submit" busy={busy} disabled={!changed}>Save</Button>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections";
|
||||
import { Admin } from "../Admin";
|
||||
|
||||
export async function generateMetadata({ params }: { params: Promise<{ section: string }> }) {
|
||||
const { section } = await params;
|
||||
return { title: ADMIN_SECTIONS[section as AdminSection]?.title ?? "Admin" };
|
||||
}
|
||||
|
||||
/** One section of admin (1.3.0): /admin/people, /deletions, /church, … (1.8.0: /admin itself is the overview). */
|
||||
export default async function AdminSectionPage({ params }: { params: Promise<{ section: string }> }) {
|
||||
const { section } = await params;
|
||||
if (section === "overview" || !(section in ADMIN_SECTIONS)) notFound();
|
||||
return <Admin section={section as AdminSection} />;
|
||||
}
|
||||
@@ -3,5 +3,5 @@ import { Admin } from "./Admin";
|
||||
export const metadata = { title: "Admin" };
|
||||
|
||||
export default function AdminPage() {
|
||||
return <Admin />;
|
||||
return <Admin section="overview" />;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call } from "@/lib/api";
|
||||
|
||||
@@ -11,9 +13,9 @@ export function Forgot({ uid }: { uid: string | null }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
{sent ? (
|
||||
<Notice tone="success">If there's an account with that email address, a link is on its way. It works for an hour. You can close this page: the link brings you back.</Notice>
|
||||
) : (
|
||||
@@ -31,6 +33,6 @@ export function Forgot({ uid }: { uid: string | null }) {
|
||||
)}
|
||||
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,4 +10,11 @@
|
||||
|
||||
body {
|
||||
@apply bg-gray-50 text-gray-900 antialiased;
|
||||
/* 1.7.0: the church's font pairing when it has one (@crosscode/ui fonts.css), else the system font. */
|
||||
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#2563eb"/>
|
||||
<stop offset="1" stop-color="#1e3a8a"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="14" fill="url(#bg)"/>
|
||||
<path d="M32 9.5 51 17v13.6c0 12.2-8.1 20.6-19 24.4-10.9-3.8-19-12.2-19-24.4V17z" fill="#fff"/>
|
||||
<circle cx="32" cy="27" r="6.6" fill="#1e3a8a"/>
|
||||
<path d="M20.6 43.2c2.2-6.6 6.4-9.4 11.4-9.4s9.2 2.8 11.4 9.4c-3.1 3.4-7 5.9-11.4 7.4-4.4-1.5-8.3-4-11.4-7.4z" fill="#1e3a8a"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 594 B |
@@ -1,8 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { BrandingProvider } from "@/components/BrandingProvider";
|
||||
import { loadBranding, rgbVars } from "@/lib/branding";
|
||||
import { loadBranding, loadChurch, rgbVars } from "@/lib/branding";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const b = await loadBranding();
|
||||
@@ -12,15 +14,16 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
||||
const b = await loadBranding();
|
||||
const [b, church] = await Promise.all([loadBranding(), loadChurch()]);
|
||||
const vars = rgbVars(b.colours.primary);
|
||||
// 1.7.0: the church's font pairing and corners (fonts.css), shared with its other sites.
|
||||
return (
|
||||
<html lang="en-ZA">
|
||||
<html lang="en-ZA" {...brandAttributes(b.style)}>
|
||||
<head>
|
||||
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
|
||||
</head>
|
||||
<body>
|
||||
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
|
||||
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded, church }}>
|
||||
{children}
|
||||
</BrandingProvider>
|
||||
</body>
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { loadBranding } from "@/lib/branding";
|
||||
import { FileText } from "lucide-react";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { NoticeText } from "@/components/NoticeText";
|
||||
import { Card } from "@/components/Panel";
|
||||
|
||||
export const metadata = { title: "Privacy notice" };
|
||||
|
||||
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||
|
||||
/** The privacy notice for everyone, signed in or not (1.3.0: in the account pages' frame, with headings). */
|
||||
export default async function PrivacyPage() {
|
||||
const branding = await loadBranding();
|
||||
const n = await fetch(`${api}/api/v2/notice`, { cache: "no-store" }).then((r) => r.json()).catch(() => null) as { title: string; body: string } | null;
|
||||
const n = await fetch(`${api}/api/v2/notice`, { cache: "no-store" }).then((r) => r.json()).catch(() => null) as { title: string; body: string; version?: number } | null;
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading>{n?.title ?? "Privacy notice"}</Heading>
|
||||
<div className="whitespace-pre-line text-sm leading-6 text-gray-700">{n?.body ?? "The privacy notice couldn't be loaded. Please try again."}</div>
|
||||
</Card>
|
||||
</Shell>
|
||||
<AppShell me={null}>
|
||||
<div className="mx-auto max-w-3xl">
|
||||
<Card className="sm:p-8">
|
||||
<div className="mb-6 flex items-start gap-3 border-b pb-5">
|
||||
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand" aria-hidden><FileText className="h-5 w-5" /></span>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{n?.title ?? "Privacy notice"}</h1>
|
||||
{n?.version && <p className="mt-1 text-sm text-gray-500">Version {n.version}</p>}
|
||||
</div>
|
||||
</div>
|
||||
{n ? <NoticeText body={n.body} /> : <p className="text-sm text-gray-700">The privacy notice couldn't be loaded. Please try again.</p>}
|
||||
</Card>
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
|
||||
@@ -10,9 +12,9 @@ export function Reset({ token }: { token: string | null }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading sub="At least 8 characters.">Choose a new password</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
@@ -28,6 +30,6 @@ export function Reset({ token }: { token: string | null }) {
|
||||
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
@@ -26,7 +27,7 @@ export function Setup() {
|
||||
<Card>
|
||||
<Heading sub="Your church's sign-in for its website, app and Cross Events.">Set up Accounts</Heading>
|
||||
{!status ? <p className="text-gray-600">Loading…</p> : !status.needed ? (
|
||||
<Notice tone="info">Accounts is already set up. <a href="/account" className="underline">Sign in</a></Notice>
|
||||
<Notice tone="info">Accounts is already set up. <Link href="/account" className="underline">Sign in</Link></Notice>
|
||||
) : (
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { LogOut } from "lucide-react";
|
||||
import { Card, Heading } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { selfSignIn } from "@/lib/api";
|
||||
|
||||
export default function SignedOutPage() {
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { NoticeText } from "@/components/NoticeText";
|
||||
import { call, type ApiError } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
@@ -80,7 +83,7 @@ export function SignIn({ uid }: { uid: string }) {
|
||||
return r;
|
||||
};
|
||||
|
||||
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
|
||||
const frame = (children: React.ReactNode) => <PublicShell><Card>{children}</Card></PublicShell>;
|
||||
|
||||
if (codes) {
|
||||
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
|
||||
@@ -88,7 +91,7 @@ export function SignIn({ uid }: { uid: string }) {
|
||||
if (!state) {
|
||||
return frame(error ? (
|
||||
<>
|
||||
<Heading>We couldn't continue</Heading>
|
||||
<Heading icon={<AlertTriangle className="h-5 w-5" />}>We couldn't continue</Heading>
|
||||
<Notice tone="error">{error.message}</Notice>
|
||||
</>
|
||||
) : <p className="text-gray-600">Loading…</p>);
|
||||
@@ -121,7 +124,7 @@ function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State;
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email"), password: f.get("password"), remember: f.get("remember") === "on" }); }}>
|
||||
<Heading sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
<Heading icon={<LogIn className="h-5 w-5" />} sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
{err}
|
||||
<Field label="Email address" name="email" type="email" autoComplete="username" required defaultValue={state.loginHint ?? ""} />
|
||||
<Field label="Password" name="password" type="password" autoComplete="current-password" required />
|
||||
@@ -144,7 +147,7 @@ function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean
|
||||
const f = new FormData(e.currentTarget);
|
||||
onSubmit({ name: f.get("name"), email: f.get("email"), phone: f.get("phone") || undefined, password: f.get("password"), acceptNotice: f.get("acceptNotice") === "on", newsEmail: f.get("newsEmail") === "on", newsWhatsApp: f.get("newsWhatsApp") === "on", remember: true });
|
||||
}}>
|
||||
<Heading sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
<Heading icon={<UserPlus className="h-5 w-5" />} sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
{err}
|
||||
<Field label="Your name" name="name" autoComplete="name" required error={fieldError("name")} />
|
||||
<Field label="Email address" name="email" type="email" autoComplete="email" required error={fieldError("email")} />
|
||||
@@ -162,7 +165,7 @@ function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean
|
||||
function CodeStep({ title, sub, busy, err, onSubmit, onResend }: { title: string; sub: React.ReactNode; busy: boolean; err: React.ReactNode; onSubmit: (code: string) => void; onResend?: () => void }) {
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("code") ?? "")); }}>
|
||||
<Heading sub={sub}>{title}</Heading>
|
||||
<Heading icon={<Mail className="h-5 w-5" />} sub={sub}>{title}</Heading>
|
||||
{err}
|
||||
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9 ]{6,7}" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||
@@ -212,7 +215,7 @@ function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Heading sub={why}>Set up two-step sign-in</Heading>
|
||||
<Heading icon={<ShieldCheck className="h-5 w-5" />} sub={why}>Set up two-step sign-in</Heading>
|
||||
{err}
|
||||
<div className="space-y-2">
|
||||
{(state.methods ?? []).map((m) => (
|
||||
@@ -243,7 +246,7 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void
|
||||
const text = codes.join("\n");
|
||||
return (
|
||||
<>
|
||||
<Heading sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<pre className="mb-4 rounded-lg bg-gray-50 p-4 text-center font-mono text-sm leading-7">{text}</pre>
|
||||
<div className="mb-4 flex gap-2">
|
||||
<Button type="button" variant="secondary" onClick={() => navigator.clipboard?.writeText(text)}>Copy</Button>
|
||||
@@ -257,9 +260,9 @@ function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void
|
||||
function NoticeStep({ state, busy, err, onAccept }: { state: State; busy: boolean; err: React.ReactNode; onAccept: () => void }) {
|
||||
return (
|
||||
<>
|
||||
<Heading sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
<Heading icon={<FileText className="h-5 w-5" />} sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
{err}
|
||||
<div className="mb-4 max-h-80 overflow-y-auto whitespace-pre-line rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">{state.notice!.body}</div>
|
||||
<div className="mb-4 max-h-80 overflow-y-auto rounded-lg border bg-gray-50 p-4"><NoticeText body={state.notice!.body} compact /></div>
|
||||
<Button type="button" busy={busy} className="w-full" onClick={onAccept}>I've read it</Button>
|
||||
</>
|
||||
);
|
||||
@@ -269,7 +272,7 @@ function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); }}>
|
||||
<Heading sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
<Heading icon={<Megaphone className="h-5 w-5" />} sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
{err}
|
||||
<Checkbox name="email" label="Yes, by email" />
|
||||
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Activity, Building2, DatabaseBackup, FileText, KeyRound, LayoutDashboard, Link2, Lock, LogIn, LogOut, Mail, Menu, ScrollText,
|
||||
ShieldCheck, Timer, User, Users, UserX, X, type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { ChurchMark } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
|
||||
/** Who's signed in, as the shell shows them (null: a public page such as the privacy notice). */
|
||||
export type ShellUser = { name: string; email: string; role: "member" | "admin" };
|
||||
|
||||
export type NavItem = { href: string; label: string; icon: LucideIcon };
|
||||
|
||||
export const ACCOUNT_NAV: NavItem[] = [
|
||||
{ href: "/account", label: "Overview", icon: LayoutDashboard },
|
||||
{ href: "/account/details", label: "Your details", icon: User },
|
||||
{ href: "/account/security", label: "Signing in", icon: ShieldCheck },
|
||||
{ href: "/account/privacy", label: "Privacy", icon: Lock },
|
||||
{ href: "/account/activity", label: "Activity", icon: Activity },
|
||||
];
|
||||
|
||||
/** 1.8.0: the admin's sections in groups, as Cross Events' settings, with the overview first. */
|
||||
export const ADMIN_GROUPS: { title: string | null; items: NavItem[] }[] = [
|
||||
{ title: null, items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] },
|
||||
{ title: "People", items: [{ href: "/admin/people", label: "People", icon: Users }, { href: "/admin/deletions", label: "Deletion requests", icon: UserX }] },
|
||||
{ title: "Church", items: [{ href: "/admin/church", label: "Church profile", icon: Building2 }, { href: "/admin/linked", label: "Linked products", icon: Link2 }] },
|
||||
{
|
||||
title: "Signing in",
|
||||
items: [{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn }, { href: "/admin/messages", label: "Email and WhatsApp", icon: Mail }, { href: "/admin/notice", label: "Privacy notice", icon: FileText }],
|
||||
},
|
||||
{
|
||||
title: "System",
|
||||
items: [{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup }, { href: "/admin/jobs", label: "Background jobs", icon: Timer }, { href: "/admin/licence", label: "Licence", icon: KeyRound }, { href: "/admin/audit", label: "Audit log", icon: ScrollText }],
|
||||
},
|
||||
];
|
||||
export const ADMIN_NAV: NavItem[] = ADMIN_GROUPS.flatMap((g) => g.items);
|
||||
|
||||
/** Signs out of Accounts and every site of the church (RP-initiated logout), ending on /signed-out. */
|
||||
export function signOutHref() {
|
||||
return `/api/oidc/session/end?client_id=accounts-self&post_logout_redirect_uri=${encodeURIComponent(`${window.location.origin}/signed-out`)}`;
|
||||
}
|
||||
|
||||
const initials = (name: string) => name.split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]!.toUpperCase()).join("") || "?";
|
||||
|
||||
function Avatar({ name, small }: { name: string; small?: boolean }) {
|
||||
return <span className={`${small ? "h-8 w-8 text-xs" : "h-10 w-10 text-sm"} flex shrink-0 items-center justify-center rounded-full bg-brand/10 font-semibold text-brand-dark`} aria-hidden>{initials(name)}</span>;
|
||||
}
|
||||
|
||||
function RoleBadge({ role }: { role: ShellUser["role"] }) {
|
||||
return role === "admin"
|
||||
? <span className="inline-block rounded-full bg-brand/10 px-2 py-0.5 text-[11px] font-medium text-brand-dark">Accounts admin</span>
|
||||
: <span className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-600">Member</span>;
|
||||
}
|
||||
|
||||
/** Counts beside a section (deletion requests waiting, say), by its address. */
|
||||
export type Badges = Record<string, number>;
|
||||
|
||||
function NavLinks({ items, active, badges, onNavigate }: { items: NavItem[]; active: string; badges?: Badges; onNavigate?: () => void }) {
|
||||
return (
|
||||
<ul className="space-y-0.5">
|
||||
{items.map((l) => {
|
||||
const Icon = l.icon;
|
||||
const on = active === l.href;
|
||||
const n = badges?.[l.href] ?? 0;
|
||||
return (
|
||||
<li key={l.href}>
|
||||
<Link href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
|
||||
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"}`}>
|
||||
<Icon className="h-4 w-4 shrink-0" aria-hidden />
|
||||
<span className="flex-1">{l.label}</span>
|
||||
{n > 0 && <span className="rounded-full bg-amber-100 px-1.5 text-xs font-semibold text-amber-900">{n}<span className="sr-only"> waiting</span></span>}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountNav({ active, onNavigate }: { active: string; onNavigate?: () => void }) {
|
||||
return (
|
||||
<div className="mb-6">
|
||||
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Your account</p>
|
||||
<nav aria-label="Your account"><NavLinks items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} /></nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AdminNav({ active, badges, onNavigate }: { active: string; badges?: Badges; onNavigate?: () => void }) {
|
||||
return (
|
||||
<nav aria-label="Admin" className="mb-6 space-y-5">
|
||||
{ADMIN_GROUPS.map((g, i) => (
|
||||
<div key={g.title ?? i}>
|
||||
<p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500">{g.title ?? "Admin"}</p>
|
||||
<NavLinks items={g.items} active={active} badges={badges} onNavigate={onNavigate} />
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sidebar: who's signed in, then the sections of the part you're in (1.8.0: your account or
|
||||
* admin, not both at once; the bar across the top switches). In the phone menu, both.
|
||||
*/
|
||||
function SidebarContent({ me, active, badges, both, onNavigate }: { me: ShellUser; active: string; badges?: Badges; both?: boolean; onNavigate?: () => void }) {
|
||||
const inAdmin = me.role === "admin" && active.startsWith("/admin");
|
||||
return (
|
||||
<>
|
||||
<div className="mb-6 flex items-center gap-3 px-1">
|
||||
<Avatar name={me.name} />
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-semibold text-gray-900">{me.name}</div>
|
||||
<RoleBadge role={me.role} />
|
||||
</div>
|
||||
</div>
|
||||
{(both || !inAdmin) && <AccountNav active={active} onNavigate={onNavigate} />}
|
||||
{me.role === "admin" && (both || inAdmin) && <AdminNav active={active} badges={badges} onNavigate={onNavigate} />}
|
||||
{!both && me.role === "admin" && (
|
||||
<Link href={inAdmin ? "/account" : "/admin"} className="flex items-center gap-2 rounded-lg border border-dashed px-3 py-2 text-sm text-gray-600 hover:border-brand/40 hover:text-brand-dark">
|
||||
{inAdmin ? <User className="h-4 w-4" aria-hidden /> : <ShieldCheck className="h-4 w-4" aria-hidden />}
|
||||
{inAdmin ? "Go to your account" : "Go to admin"}
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame of the account and admin pages (1.3.0, as Cross Events' dashboard): the church's logo
|
||||
* and name across the top, a sidebar of sections, the page on a light grey, and a dark footer.
|
||||
* Without `me` (a public page) there's no sidebar. `active` is the current section's address.
|
||||
*/
|
||||
export function AppShell({ me, active = "", badges, children }: { me: ShellUser | null; active?: string; badges?: Badges; children: React.ReactNode }) {
|
||||
const b = useBranding();
|
||||
const [open, setOpen] = useState(false);
|
||||
const top = "text-sm border-b-2 pb-0.5 transition-colors";
|
||||
const inAdmin = active.startsWith("/admin");
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col bg-gray-50">
|
||||
<a href="#main" className="sr-only focus:not-sr-only focus:absolute focus:left-4 focus:top-4 focus:z-50 focus:rounded focus:bg-white focus:px-3 focus:py-2">Skip to content</a>
|
||||
<header className="sticky top-0 z-40 bg-white shadow-md">
|
||||
<div className="mx-auto flex max-w-7xl items-center justify-between gap-3 px-4 py-3">
|
||||
<Link href={me ? "/account" : "/"} className="flex min-w-0 items-center gap-2">
|
||||
<ChurchMark branding={b} />
|
||||
<span className="truncate text-lg font-bold text-brand-dark sm:text-xl">{b.name}</span>
|
||||
</Link>
|
||||
{me && (
|
||||
<>
|
||||
<div className="hidden items-center gap-6 md:flex">
|
||||
<Link href="/account" className={`${top} ${!inAdmin ? "border-brand font-medium text-brand-dark" : "border-transparent text-gray-700 hover:text-brand"}`}>Your account</Link>
|
||||
{me.role === "admin" && <Link href="/admin" className={`${top} ${inAdmin ? "border-brand font-medium text-brand-dark" : "border-transparent text-gray-700 hover:text-brand"}`}>Admin</Link>}
|
||||
<a href="/signed-out" onClick={(e) => { e.preventDefault(); window.location.assign(signOutHref()); }} className={`${top} inline-flex items-center gap-1.5 border-transparent text-gray-700 hover:text-brand`}>
|
||||
<LogOut className="h-4 w-4" aria-hidden /> Sign out
|
||||
</a>
|
||||
</div>
|
||||
<button type="button" onClick={() => setOpen(true)} aria-label="Open the menu" aria-expanded={open} className="rounded-md p-2 hover:bg-gray-100 md:hidden">
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{me && open && (
|
||||
<div className="fixed inset-0 z-50 md:hidden" role="dialog" aria-modal="true" aria-label="Menu">
|
||||
<button type="button" className="absolute inset-0 bg-black/30" aria-label="Close the menu" onClick={() => setOpen(false)} />
|
||||
<div className="absolute inset-y-0 left-0 flex w-72 max-w-[85vw] flex-col overflow-y-auto bg-white p-4 shadow-xl">
|
||||
<button type="button" onClick={() => setOpen(false)} aria-label="Close the menu" className="mb-2 self-end rounded-md p-2 hover:bg-gray-100"><X className="h-5 w-5" /></button>
|
||||
<SidebarContent me={me} active={active} badges={badges} both onNavigate={() => setOpen(false)} />
|
||||
<a href="/signed-out" onClick={(e) => { e.preventDefault(); window.location.assign(signOutHref()); }} className="mt-auto flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50">
|
||||
<LogOut className="h-4 w-4" aria-hidden /> Sign out
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-1">
|
||||
{me && (
|
||||
<aside className="hidden w-64 shrink-0 border-r bg-white p-4 md:block">
|
||||
<div className="sticky top-20"><SidebarContent me={me} active={active} badges={badges} /></div>
|
||||
</aside>
|
||||
)}
|
||||
<main id="main" className="min-w-0 flex-1 p-4 sm:p-6">{children}</main>
|
||||
</div>
|
||||
|
||||
<footer className="bg-gray-900 py-6 text-center text-sm text-white">
|
||||
<p>© {new Date().getFullYear()} {b.name}. One church account for all its sites and apps.</p>
|
||||
<div className="mt-2 space-x-4">
|
||||
<a href="/privacy" className="text-gray-300 hover:underline">Privacy notice</a>
|
||||
{me && <Link href="/account/activity" className="text-gray-300 hover:underline">Your sign-ins</Link>}
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A page's title and a line under it, at the top of the main column; with the section's icon. */
|
||||
export function PageTitle({ children, sub, icon: Icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: LucideIcon }) {
|
||||
return (
|
||||
<div className="mb-6 flex items-start gap-3">
|
||||
{Icon && <span className="mt-0.5 hidden h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-brand/10 text-brand sm:flex" aria-hidden><Icon className="h-5 w-5" /></span>}
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
|
||||
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** While a page loads its data: the frame without a sidebar yet. */
|
||||
export function ShellLoading() {
|
||||
return (
|
||||
<AppShell me={null}>
|
||||
<p className="text-sm text-gray-500" role="status">Loading…</p>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext } from "react";
|
||||
import type { FooterChurch } from "@crosscode/ui";
|
||||
|
||||
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
|
||||
/** `church` (1.7.0): the profile for the shared footer, null when it couldn't be loaded. */
|
||||
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean; church?: FooterChurch | null };
|
||||
|
||||
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from "react";
|
||||
|
||||
/**
|
||||
* A privacy notice's text (1.3.0): a line starting "## " is a heading, "• " (or "- ") a bullet,
|
||||
* anything else a paragraph. Notices published before 1.3.0 are plain paragraphs and look as before.
|
||||
*/
|
||||
export function NoticeText({ body, compact = false }: { body: string; compact?: boolean }) {
|
||||
const blocks: React.ReactNode[] = [];
|
||||
let bullets: string[] = [];
|
||||
const flush = () => {
|
||||
if (!bullets.length) return;
|
||||
blocks.push(<ul key={`u${blocks.length}`} className="mb-3 list-disc space-y-1 pl-5">{bullets.map((b, i) => <li key={i}>{b}</li>)}</ul>);
|
||||
bullets = [];
|
||||
};
|
||||
for (const raw of body.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (/^[•-]\s+/.test(line)) { bullets.push(line.replace(/^[•-]\s+/, "")); continue; }
|
||||
flush();
|
||||
if (!line) continue;
|
||||
if (line.startsWith("## ")) blocks.push(<h2 key={`h${blocks.length}`} className={`${compact ? "mt-4 text-sm" : "mt-6 text-base"} mb-2 font-semibold text-gray-900 first:mt-0`}>{line.slice(3)}</h2>);
|
||||
else blocks.push(<p key={`p${blocks.length}`} className="mb-3">{line}</p>);
|
||||
}
|
||||
flush();
|
||||
return <div className={`${compact ? "text-sm" : "text-[15px]"} leading-relaxed text-gray-700`}>{blocks}</div>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import React from "react";
|
||||
|
||||
/**
|
||||
* The account and admin pages' cards (1.3.0, as Cross Events' settings): a white panel with a
|
||||
* quiet border, and a header with an icon in a tile of the church's colour. Same names and props
|
||||
* as @crosscode/ui's Card and Heading, which the sign-in pages keep.
|
||||
*/
|
||||
export function Card({ children, className }: { children: React.ReactNode; className?: string }) {
|
||||
return <section className={`rounded-xl border bg-white p-5 shadow-sm ${className ?? ""}`}>{children}</section>;
|
||||
}
|
||||
|
||||
export function Heading({ children, sub, icon }: { children: React.ReactNode; sub?: React.ReactNode; icon?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-4 flex items-start gap-3">
|
||||
{icon && <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/10 text-brand" aria-hidden>{icon}</span>}
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-lg font-semibold text-gray-900">{children}</h2>
|
||||
{sub && <p className="mt-0.5 text-xs text-gray-500">{sub}</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { ChurchFooter, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
|
||||
/**
|
||||
* The frame of the public pages (sign in, forgot, reset, signed out, confirm email) with the
|
||||
* church's shared footer (1.7.0, WEBSITE-1.0-PLAN §9): its service times, contact and links to its
|
||||
* other sites, as on the Website and Cross Events.
|
||||
*/
|
||||
export function PublicShell({ children }: { children: React.ReactNode }) {
|
||||
const branding = useBranding();
|
||||
const footer = branding.church ? <ChurchFooter church={branding.church} current="accounts" privacyUrl="/privacy" /> : undefined;
|
||||
return <Shell branding={branding} footer={footer}>{children}</Shell>;
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { FooterChurch } from "@crosscode/ui";
|
||||
|
||||
/** The church's branding from the backend, for the server-rendered frame of every page. */
|
||||
export type BrandingData = {
|
||||
name: string;
|
||||
shortName: string | null;
|
||||
logoUrl: string | null;
|
||||
colours: { primary: string; accent: string | null };
|
||||
/** 1.7.0: the font pairing and corners (null: not picked). */
|
||||
style?: { fontPairing: string | null; corners: string | null };
|
||||
signupEnabled: boolean;
|
||||
setupNeeded: boolean;
|
||||
};
|
||||
@@ -20,6 +24,17 @@ export async function loadBranding(): Promise<BrandingData> {
|
||||
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
|
||||
}
|
||||
|
||||
/** The church profile (`crosscode.church/1`) for the shared footer (1.7.0), or null while it can't be had. */
|
||||
export async function loadChurch(): Promise<FooterChurch | null> {
|
||||
try {
|
||||
const res = await fetch(`${api}/api/church/v1`, { next: { revalidate: 60 } });
|
||||
if (res.ok) return (await res.json()) as FooterChurch;
|
||||
} catch {
|
||||
// As loadBranding: the page works without it.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
|
||||
export function rgbVars(hex: string): { brand: string; dark: string } {
|
||||
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* The admin's sections: one address each, in groups down the side (components/AppShell.tsx), and a
|
||||
* tile each on the overview. 1.8.0: /admin is the overview (as Cross Events' admin dashboard);
|
||||
* People moved to /admin/people.
|
||||
*/
|
||||
export const ADMIN_SECTIONS = {
|
||||
overview: { path: "/admin", title: "Admin", sub: "How Accounts stands, what needs you, and every setting.", tile: "" },
|
||||
people: { path: "/admin/people", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site.", tile: "Find someone, reset their two-step sign-in, make an admin" },
|
||||
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account.", tile: "Approve or cancel people's requests to delete their account" },
|
||||
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites.", tile: "Name, logo, colours and contact details for every site" },
|
||||
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here.", tile: "The sites and apps that sign people in here" },
|
||||
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in.", tile: "Who can make an account, two-step sign-in, staying signed in" },
|
||||
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices.", tile: "How sign-in codes and password links are sent" },
|
||||
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes.", tile: "What people read before they first sign in" },
|
||||
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server.", tile: "Back up now, download a copy, how many to keep" },
|
||||
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away.", tile: "What runs on a schedule, and when" },
|
||||
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code.", tile: "The connection to Cross Code" },
|
||||
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here.", tile: "Who changed what, and when" },
|
||||
} as const;
|
||||
export type AdminSection = keyof typeof ADMIN_SECTIONS;
|
||||
@@ -29,5 +29,5 @@ export function proxy(request: NextRequest) {
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [{ source: "/((?!api|_next/static|_next/image|favicon.ico).*)", missing: [{ type: "header", key: "next-router-prefetch" }] }],
|
||||
matcher: [{ source: "/((?!api|_next/static|_next/image|favicon.ico|icon.svg).*)", missing: [{ type: "header", key: "next-router-prefetch" }] }],
|
||||
};
|
||||
|
||||
@@ -13,8 +13,9 @@ curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/ma
|
||||
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
|
||||
```
|
||||
|
||||
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
|
||||
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
|
||||
Add `--central` on the central (FastPanel) server: there the agent only runs `check-ports`,
|
||||
`probe-ports`, `status`, `update-agent`, and `frp-read` / `frp-write` (frps's config, from the
|
||||
server's page on the Hub; agent 1.4.0+). The script installs Node 24 if needed, the agent in
|
||||
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
|
||||
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
|
||||
`crosscode-agent.service`.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# What's new in the server agent
|
||||
|
||||
What each version of the Cross Code server agent changes, for whoever runs the Hub. The Hub shows
|
||||
these notes on its Releases page and when you pick a version under Update agent.
|
||||
|
||||
<!--
|
||||
How this file is used: the Cross Code Hub reads it from main every 15 minutes (release source
|
||||
"Server agent", tags agent@1.2.3) and shows a section only once its version is tagged, so write it
|
||||
before tagging; fixes to old sections show straight away. Each version is a "## 1.2.3" heading; add
|
||||
"— urgent" (or "security") to the heading for a security or serious bug fix. Under it, lines
|
||||
starting with "- " show as a list and other lines as paragraphs.
|
||||
Write for the person updating servers: what the agent can now do from the Hub, and which Hub or
|
||||
contracts version needs it. The developer log is the commit history of apps/agent.
|
||||
-->
|
||||
|
||||
## 1.7.0
|
||||
|
||||
- **Demo scenarios.** The Hub (2.26.0 and later) can load a whole demo church on a demo client:
|
||||
Accounts first, then Cross Events, the Website and the App, the same church and people in each.
|
||||
It's one job: the server loads **whatever the client has installed** and skips the rest, so a
|
||||
client with only Accounts and the Website gets both. Every product's release is checked first
|
||||
(Accounts 1.9.0, Events 3.8.0, Website 1.8.0); if one fails part-way, the report says which
|
||||
products are out of step. The agent also runs single demo jobs for Accounts and (from App
|
||||
1.0.0) the Church App. Single-product demo data works as before.
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- **Demo data for the Church Website.** The Hub (2.25.0 and later) can load one of the Website's
|
||||
eight demo churches on a demo site, as it already could for Cross Events. Needs Website 1.3.0 on
|
||||
the site. Cross Events' demo data works as before.
|
||||
|
||||
## 1.5.0
|
||||
|
||||
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
|
||||
those go, and the church keeps the others. Naming every product it still has removes the whole
|
||||
church, so the last product to go takes the church with it. Before, uninstalling a church's Cross
|
||||
Events also removed its Accounts.
|
||||
- The Hub (2.12.0 and later) uninstalls one product only on servers with this agent; older agents
|
||||
can only remove the whole church.
|
||||
|
||||
## 1.4.0
|
||||
|
||||
- **frp's config from the Hub.** The agent finds frps's config (central server) or frpc's (church
|
||||
server) wherever it is: the path set on the Hub, the `-c` in the systemd unit, or the usual places.
|
||||
It reads INI and TOML.
|
||||
- **Changing it from the Hub:** the agent checks the new file with `frp* verify`, keeps a backup,
|
||||
restarts frp if asked, and puts the old file back if frp doesn't start. Secret values never leave
|
||||
the server.
|
||||
- **Ports checked before an install:** the Hub asks this server and the central server which ports
|
||||
are free, so a new install gets ports free on both.
|
||||
- Needed for frp config on a server's page and port checks (Hub 2.11.0).
|
||||
|
||||
## 1.3.1
|
||||
|
||||
- **Fix:** 1.3.0 reported itself as 1.2.0, so the Hub refused its .env jobs. It now reports its
|
||||
real version. Install this instead of 1.3.0.
|
||||
|
||||
## 1.3.0
|
||||
|
||||
- **A site's .env from the Hub.** The agent reads an install's .env (secret values hidden) and
|
||||
changes it: one file at a time, rebuilding the site when its frontend settings changed,
|
||||
restarting it, and putting the old file back if the site doesn't answer.
|
||||
- Needed for the Settings (.env) tab on an install's page (Hub 2.8.0).
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- **Demo data from the Hub.** The agent loads a demo profile onto a site marked as a demo: a backup
|
||||
first, then the demo data, keeping one admin account.
|
||||
- Needed for demo sites (Hub 2.4.0).
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- **Fix:** the server's stats now keep going while a long job runs. Before, a 30-minute install
|
||||
stopped them and the Hub alerted that the server was down.
|
||||
- **Fix:** 1.1.0 reported itself as 1.0.1; it now reports its real version.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- **Accounts installs.** The agent installs Accounts, and adds a product next to a church's others
|
||||
on the same server (with the ports and release the Hub chose).
|
||||
|
||||
## 1.0.1
|
||||
|
||||
- **Fix:** on the central server, Check status failed (it has no `crosscode` script). It now answers
|
||||
with its own stats, including whether frps is running.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- **The first server agent.** It polls the Hub every 30 seconds for signed jobs, runs the
|
||||
`crosscode` script for them (install, update, status, export, uninstall), sends the results, and
|
||||
sends the server's stats every minute. It listens on no port: every request goes out to the Hub.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.2.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",
|
||||
|
||||
+17
-48
@@ -1,51 +1,15 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { paths } from "./paths";
|
||||
import type { FrpSettings } from "./frp";
|
||||
import { portAllowed } from "./frp";
|
||||
|
||||
export { parseFrpsIni, portAllowed } from "./frp";
|
||||
|
||||
/**
|
||||
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
|
||||
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
|
||||
* The central server (AGENT-1.0-PLAN §6): the `check-ports` job after an install. Are the new
|
||||
* tunnel's ports allowed by frps, open, and bound to 127.0.0.1 only? frps's config is found and
|
||||
* read by ./frp.ts (INI or TOML, wherever it is).
|
||||
*/
|
||||
|
||||
export interface FrpsSettings {
|
||||
proxyBindAddr: string | null;
|
||||
allowPorts: string | null;
|
||||
}
|
||||
|
||||
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
|
||||
export function parseFrpsIni(text: string): FrpsSettings {
|
||||
let inCommon = false;
|
||||
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
|
||||
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
|
||||
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
|
||||
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
|
||||
try {
|
||||
return parseFrpsIni(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
|
||||
export function portAllowed(port: number, allowPorts: string | null): boolean {
|
||||
if (!allowPorts) return true;
|
||||
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
|
||||
const [a, b] = range.split("-").map((n) => Number(n.trim()));
|
||||
if (!Number.isFinite(a)) return false;
|
||||
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
|
||||
});
|
||||
}
|
||||
|
||||
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
|
||||
export function parseSs(text: string): Map<number, string[]> {
|
||||
const out = new Map<number, string[]>();
|
||||
@@ -72,11 +36,16 @@ export interface PortCheck {
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
|
||||
export function checkPorts(
|
||||
ports: number[],
|
||||
frps: Pick<FrpSettings, "proxyBindAddr" | "allowPorts"> | null,
|
||||
listening: Map<number, string[]>,
|
||||
configPath: string | null = null,
|
||||
): { ports: PortCheck[]; proxyBindAddr: string | null; configPath: string | null; warnings: string[] } {
|
||||
const warnings: string[] = [];
|
||||
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
|
||||
if (!frps) warnings.push(configPath ? `frps's config isn't at ${configPath} (Hub → the central server → frp config).` : "frps's config wasn't found (Hub → the central server → frp config: set where it is).");
|
||||
const bind = frps?.proxyBindAddr ?? null;
|
||||
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
|
||||
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 (frps.toml: proxyBindAddr = "127.0.0.1") in ${configPath ?? "frps's config"}.`);
|
||||
const results = ports.map((port) => {
|
||||
const addrs = listening.get(port) ?? [];
|
||||
const allowed = portAllowed(port, frps?.allowPorts ?? null);
|
||||
@@ -86,9 +55,9 @@ export function checkPorts(ports: number[], frps: FrpsSettings | null, listening
|
||||
for (const r of results) {
|
||||
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
|
||||
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
|
||||
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
|
||||
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1 (${(listening.get(r.port) ?? []).join(", ")}).`);
|
||||
}
|
||||
return { ports: results, proxyBindAddr: bind, warnings };
|
||||
return { ports: results, proxyBindAddr: bind, configPath, warnings };
|
||||
}
|
||||
|
||||
export function listeningNow(): Promise<Map<number, string[]>> {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { agent } from "@crosscode/contracts";
|
||||
/**
|
||||
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
|
||||
* as an array passed straight to the process (never through a shell). Jobs the agent handles
|
||||
* itself (update-agent, check-ports) have none.
|
||||
* itself (update-agent, check-ports, frp-read, frp-write, probe-ports) have none.
|
||||
*
|
||||
* `--config <file>` is added by the runner when the job brings config; `--json` always.
|
||||
*/
|
||||
@@ -48,19 +48,45 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
|
||||
return ["adopt", job.args.church, "--undo"];
|
||||
case "restart":
|
||||
return ["restart", job.args.church, ...(job.args.product ? [job.args.product] : [])];
|
||||
case "seed-demo":
|
||||
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
|
||||
case "env-read":
|
||||
return ["env", job.args.church, job.args.product];
|
||||
case "env-set": {
|
||||
// Each value is its own argument (no shell), so spaces and quotes in values are safe.
|
||||
const out = ["env", job.args.church, job.args.product, "--file", job.args.file];
|
||||
for (const [name, value] of Object.entries(job.args.set)) out.push("--set", `${name}=${value}`);
|
||||
for (const name of job.args.unset) out.push("--unset", name);
|
||||
if (job.args.restart) out.push("--restart");
|
||||
return out;
|
||||
}
|
||||
case "seed-demo": {
|
||||
// 1.6.0: the Website's demo names the product; Events' (no product) keeps its old form.
|
||||
// 1.7.0: the App's and Accounts' too, and a demo scenario passed on (`--scenario`), so each
|
||||
// product can tell a scenario load from a single one.
|
||||
const a = job.args;
|
||||
const product = a.product && a.product !== "events" ? [a.product] : [];
|
||||
return ["demo", a.church, ...product, "--profile", a.profile,
|
||||
...(a.scenario ? ["--scenario", a.scenario] : []),
|
||||
...(a.adminEmail ? ["--admin-email", a.adminEmail] : [])];
|
||||
}
|
||||
case "seed-scenario":
|
||||
// 1.7.0: a whole demo scenario. No product named: the script loads every product the church
|
||||
// has on this server, Accounts first, and skips the others.
|
||||
return ["demo", job.args.church, "--scenario", job.args.scenario, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
|
||||
case "export":
|
||||
if (!opts.exportFile) throw new Error("export needs a file to write");
|
||||
return ["export", job.args.church, "--out", opts.exportFile];
|
||||
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
|
||||
case "uninstall":
|
||||
return ["uninstall", job.args.church, "--confirm", job.args.church];
|
||||
// 1.5.0: only the products named go (the church keeps its others); none named: the church.
|
||||
return ["uninstall", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
|
||||
case "purge":
|
||||
return ["purge", job.args.church, "--confirm", job.args.church];
|
||||
return ["purge", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
|
||||
case "status":
|
||||
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
|
||||
case "update-agent":
|
||||
case "check-ports":
|
||||
case "frp-read":
|
||||
case "frp-write":
|
||||
case "probe-ports":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* frp's config on this server (agent 1.4.0): frps's on the central server, frpc's on a church
|
||||
* server. The agent finds the file itself (the path set from the Hub, else the systemd unit's
|
||||
* `-c`, else a usual place), reads frp's two formats (INI and TOML), hides secret values before
|
||||
* anything leaves the server, and writes a new file from the Hub the careful way: secrets put
|
||||
* back, `verify`, a backup, a restart, and the old file back when the service doesn't come up.
|
||||
*/
|
||||
|
||||
export type FrpService = "frps" | "frpc";
|
||||
export type FrpSource = (typeof agent.FRP_CONFIG_SOURCES)[number];
|
||||
export const serviceFor = (mode: agent.AgentMode): FrpService => (mode === "central" ? "frps" : "frpc");
|
||||
|
||||
// ─── Where the file is ────────────────────────────────────────────────────────
|
||||
|
||||
/** frps.toml, frpc.ini, frps-main.toml … */
|
||||
const FRP_FILE = /^frp[A-Za-z0-9._-]*\.(ini|toml)$/;
|
||||
|
||||
const rememberedFile = () => path.join(paths.stateDir, "frp.json");
|
||||
|
||||
/** The path set from the Hub (an `frp-read` with a path), if any. */
|
||||
export function rememberedPath(): string | null {
|
||||
try {
|
||||
const p = JSON.parse(fs.readFileSync(rememberedFile(), "utf8")).path;
|
||||
return typeof p === "string" && path.isAbsolute(p) && FRP_FILE.test(path.basename(p)) ? p : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberPath(p: string): void {
|
||||
fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(rememberedFile(), `${JSON.stringify({ path: p, at: new Date().toISOString() })}\n`, { mode: 0o600 });
|
||||
}
|
||||
|
||||
/** `-c <file>`, `-c=<file>`, `--config <file>` or `--config=<file>` in a command line. */
|
||||
export function configFromCommand(argv: string): string | null {
|
||||
const parts = argv.trim().split(/\s+/);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const a = parts[i]!;
|
||||
const eq = /^(?:-c|--config)=(.+)$/.exec(a);
|
||||
if (eq) return eq[1]!;
|
||||
if ((a === "-c" || a === "--config") && parts[i + 1]) return parts[i + 1]!;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The config and the binary from `systemctl show <unit> -p ExecStart --value` ("{ path=… ; argv[]=… ; … }"). */
|
||||
export function parseExecStart(text: string): { config: string | null; bin: string | null } {
|
||||
const argv = /argv\[\]=([^;]*)/.exec(text)?.[1]?.trim() ?? text.trim();
|
||||
const bin = argv.split(/\s+/)[0] || null;
|
||||
return { config: configFromCommand(argv), bin: bin && bin.startsWith("/") ? bin : null };
|
||||
}
|
||||
|
||||
function execText(cmd: string, args: string[], timeout = 10_000): Promise<{ ok: boolean; out: string; err: string; missing: boolean }> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({
|
||||
ok: !err, out: String(stdout ?? ""), err: String(stderr ?? "") || (err ? err.message : ""), missing: (err as NodeJS.ErrnoException | null)?.code === "ENOENT",
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function fromSystemd(service: FrpService): Promise<{ config: string | null; bin: string | null }> {
|
||||
const r = await execText("systemctl", ["show", service, "-p", "ExecStart", "--value"]);
|
||||
return r.ok ? parseExecStart(r.out) : { config: null, bin: null };
|
||||
}
|
||||
|
||||
/** Where frp is usually kept, in the order the agent looks. */
|
||||
export function usualPlaces(service: FrpService): string[] {
|
||||
const dirs = ["/etc/frp", `/etc/${service}`, "/usr/local/etc/frp", "/usr/local/frp", "/opt/frp", `/opt/${service}`, "/root/frp"];
|
||||
return dirs.flatMap((d) => [`${d}/${service}.toml`, `${d}/${service}.ini`]);
|
||||
}
|
||||
|
||||
export interface FoundConfig {
|
||||
path: string | null;
|
||||
source: FrpSource | null;
|
||||
/** frps / frpc as the systemd unit runs it (for `verify`), else the name on PATH. */
|
||||
bin: string;
|
||||
looked: string[];
|
||||
}
|
||||
|
||||
const exists = (f: string) => { try { return fs.statSync(f).isFile(); } catch { return false; } };
|
||||
|
||||
let cache: { at: number; mode: agent.AgentMode; found: FoundConfig } | null = null;
|
||||
|
||||
/** The config this server's frp uses. The Hub's path wins (even when the file isn't there: the Hub then says so). */
|
||||
export async function findConfig(mode: agent.AgentMode, opts: { fresh?: boolean } = {}): Promise<FoundConfig> {
|
||||
if (!opts.fresh && cache && cache.mode === mode && Date.now() - cache.at < 5 * 60_000) return cache.found;
|
||||
const service = serviceFor(mode);
|
||||
const unit = await fromSystemd(service);
|
||||
const bin = unit.bin ?? service;
|
||||
const looked: string[] = [];
|
||||
let found: FoundConfig | null = null;
|
||||
const hub = rememberedPath();
|
||||
// The old setting (agent 1.0–1.3) still works, for a server that set it in the unit.
|
||||
const env = mode === "central" ? process.env.CROSSCODE_FRPS_INI : process.env.CROSSCODE_FRPC_INI;
|
||||
if (hub) found = { path: hub, source: "hub", bin, looked };
|
||||
else if (env) found = { path: env, source: "hub", bin, looked };
|
||||
else {
|
||||
const candidates: Array<[string, FrpSource]> = [];
|
||||
if (unit.config) candidates.push([unit.config, "systemd"]);
|
||||
for (const p of usualPlaces(service)) candidates.push([p, "usual-place"]);
|
||||
for (const [p, source] of candidates) {
|
||||
looked.push(p);
|
||||
if (exists(p)) { found = { path: p, source, bin, looked: [] }; break; }
|
||||
}
|
||||
}
|
||||
const result = found ?? { path: null, source: null, bin, looked: looked.slice(0, 20) };
|
||||
cache = { at: Date.now(), mode, found: result };
|
||||
return result;
|
||||
}
|
||||
|
||||
export function forgetFound(): void {
|
||||
cache = null;
|
||||
}
|
||||
|
||||
// ─── Reading INI and TOML ─────────────────────────────────────────────────────
|
||||
|
||||
export type FrpFormat = "ini" | "toml";
|
||||
export const formatOf = (file: string, text = ""): FrpFormat => (file.endsWith(".toml") ? "toml" : file.endsWith(".ini") ? "ini" : /^\s*\[common\]/m.test(text) ? "ini" : "toml");
|
||||
|
||||
interface Line {
|
||||
/** `[common]`, `[[proxies]]`: the header the line is under ("" before any), with how many came before it. */
|
||||
section: string;
|
||||
sectionIndex: number;
|
||||
key: string;
|
||||
/** The value as written, after `=` (quotes kept, comments after it dropped for TOML). */
|
||||
raw: string;
|
||||
/** The value without quotes. */
|
||||
value: string;
|
||||
/** Where `raw` starts and ends in the line. */
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
function unquote(v: string): string {
|
||||
const t = v.trim();
|
||||
if ((t.startsWith('"') && t.endsWith('"') && t.length >= 2) || (t.startsWith("'") && t.endsWith("'") && t.length >= 2)) return t.slice(1, -1);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Each `key = value` line, with the section it's in. */
|
||||
export function lines(text: string, format: FrpFormat): Array<Line | null> {
|
||||
let section = "";
|
||||
const seen = new Map<string, number>();
|
||||
let sectionIndex = 0;
|
||||
return text.split("\n").map((rawLine) => {
|
||||
const line = rawLine.replace(/\r$/, "");
|
||||
const t = line.trim();
|
||||
if (!t || t.startsWith("#") || t.startsWith(";")) return null;
|
||||
const header = /^(\[\[?[^\]]+\]\]?)\s*(#.*)?$/.exec(t);
|
||||
if (header) {
|
||||
section = header[1]!.replace(/\s+/g, "");
|
||||
sectionIndex = seen.get(section) ?? 0;
|
||||
seen.set(section, sectionIndex + 1);
|
||||
return null;
|
||||
}
|
||||
const m = /^(\s*)([A-Za-z0-9_.-]+|"[^"]+")(\s*=\s*)(.*)$/.exec(line);
|
||||
if (!m) return null;
|
||||
let raw = m[4]!;
|
||||
if (format === "toml") {
|
||||
// A comment after the value (outside quotes).
|
||||
let q: string | null = null;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const c = raw[i]!;
|
||||
if (q) { if (c === q && raw[i - 1] !== "\\") q = null; continue; }
|
||||
if (c === '"' || c === "'") q = c;
|
||||
else if (c === "#") { raw = raw.slice(0, i); break; }
|
||||
}
|
||||
}
|
||||
raw = raw.replace(/\s+$/, "");
|
||||
const start = m[1]!.length + m[2]!.length + m[3]!.length;
|
||||
return { section, sectionIndex, key: m[2]!.replace(/"/g, ""), raw, value: unquote(raw), start, end: start + raw.length };
|
||||
});
|
||||
}
|
||||
|
||||
export interface FrpSettings {
|
||||
proxyBindAddr: string | null;
|
||||
allowPorts: string | null;
|
||||
/** Ports frpc's proxies use (remote and local), or frps's own ports (bind, dashboard …). */
|
||||
usedPorts: number[];
|
||||
}
|
||||
|
||||
/** TOML's allowPorts = [{ start = 2000, end = 3000 }, { single = 3001 }] → "2000-3000,3001". */
|
||||
export function tomlAllowPorts(text: string): string | null {
|
||||
const m = /^\s*allowPorts\s*=\s*\[([\s\S]*?)\]\s*$/m.exec(text);
|
||||
if (!m) return null;
|
||||
const out: string[] = [];
|
||||
for (const obj of m[1]!.matchAll(/\{([^}]*)\}/g)) {
|
||||
const single = /single\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
|
||||
const start = /start\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
|
||||
const end = /end\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
|
||||
if (single) out.push(single);
|
||||
else if (start && end) out.push(`${start}-${end}`);
|
||||
else if (start) out.push(start);
|
||||
}
|
||||
return out.length ? out.join(",") : null;
|
||||
}
|
||||
|
||||
const PORT_KEYS = /^(remote_?port|remotePort|local_?port|localPort|bind_?port|bindPort|kcp_?bind_?port|kcpBindPort|quic_?bind_?port|quicBindPort|vhost_?http_?port|vhostHTTPPort|vhost_?https_?port|vhostHTTPSPort|dashboard_?port|admin_?port|webServer\.port|port|tcpmux_?httpconnect_?port|tcpmuxHTTPConnectPort)$/;
|
||||
|
||||
export function parseSettings(text: string, format: FrpFormat): FrpSettings {
|
||||
const all = lines(text, format).filter((l): l is Line => !!l);
|
||||
const used = new Set<number>();
|
||||
for (const l of all) {
|
||||
if (!PORT_KEYS.test(l.key)) continue;
|
||||
// INI: `remote_port = 6000`; frpc's `local_port` of a proxy is a port on the server too.
|
||||
for (const n of l.value.split(/[,\s]+/)) if (/^\d+$/.test(n)) used.add(Number(n));
|
||||
}
|
||||
if (format === "ini") {
|
||||
const common = all.filter((l) => l.section === "[common]");
|
||||
const get = (k: string) => common.find((l) => l.key === k)?.value || null;
|
||||
return { proxyBindAddr: get("proxy_bind_addr"), allowPorts: get("allow_ports"), usedPorts: [...used].sort((a, b) => a - b) };
|
||||
}
|
||||
const top = all.filter((l) => l.section === "");
|
||||
return {
|
||||
proxyBindAddr: top.find((l) => l.key === "proxyBindAddr")?.value || null,
|
||||
allowPorts: tomlAllowPorts(text),
|
||||
usedPorts: [...used].sort((a, b) => a - b),
|
||||
};
|
||||
}
|
||||
|
||||
/** Keeps the old helper's shape (agent ≤ 1.3 tests and stats). */
|
||||
export function parseFrpsIni(text: string): { proxyBindAddr: string | null; allowPorts: string | null } {
|
||||
const s = parseSettings(text, "ini");
|
||||
return { proxyBindAddr: s.proxyBindAddr, allowPorts: s.allowPorts };
|
||||
}
|
||||
|
||||
// ─── Secrets ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/** token, auth.token, dashboard_pwd, webServer.password, oidc client secret, privilege_token … */
|
||||
const SECRET_KEY = /(token|pwd|passw(or)?d|secret|private_?key|privateKey|credential)/i;
|
||||
export const isSecretKey = (key: string): boolean => SECRET_KEY.test(key);
|
||||
/** A secret key, or an inline table with one in it (auth = { token = "…" }). */
|
||||
const INLINE_SECRET = /[{,]\s*[A-Za-z0-9_.]*(token|pwd|passw(or)?d|secret|private_?key|credential)[A-Za-z0-9_]*\s*=/i;
|
||||
const isSecretLine = (l: Line): boolean => isSecretKey(l.key) || INLINE_SECRET.test(l.raw);
|
||||
|
||||
const idOf = (l: Line) => `${l.section}#${l.sectionIndex}/${l.key}`;
|
||||
const nameOf = (l: Line) => (l.section && !l.section.startsWith("[[") && l.section !== "[common]" ? `${l.section.replace(/[[\]]/g, "")}.${l.key}` : l.key);
|
||||
|
||||
function hiddenRaw(raw: string): string {
|
||||
const t = raw.trim();
|
||||
if (t.startsWith('"')) return `"${agent.FRP_HIDDEN}"`;
|
||||
if (t.startsWith("'")) return `'${agent.FRP_HIDDEN}'`;
|
||||
return agent.FRP_HIDDEN;
|
||||
}
|
||||
|
||||
/** The file with secret values replaced, and their names. */
|
||||
export function hideSecrets(text: string, format: FrpFormat): { content: string; hidden: string[] } {
|
||||
const hidden: string[] = [];
|
||||
const src = text.split("\n");
|
||||
lines(text, format).forEach((l, i) => {
|
||||
if (!l || !isSecretLine(l) || !l.value) return;
|
||||
const line = src[i]!;
|
||||
src[i] = line.slice(0, l.start) + hiddenRaw(l.raw) + line.slice(l.end);
|
||||
hidden.push(nameOf(l));
|
||||
});
|
||||
return { content: src.join("\n"), hidden: [...new Set(hidden)].slice(0, 50) };
|
||||
}
|
||||
|
||||
/**
|
||||
* A file from the Hub with the server's secret values put back. Refused when it changes a secret,
|
||||
* or has a hidden value the server's file has no value for.
|
||||
*/
|
||||
export function restoreSecrets(incoming: string, current: string, format: FrpFormat): { ok: true; content: string } | { ok: false; message: string } {
|
||||
const now = new Map<string, Line>();
|
||||
for (const l of lines(current, format)) if (l && isSecretLine(l)) now.set(idOf(l), l);
|
||||
const src = incoming.split("\n");
|
||||
const parsed = lines(incoming, format);
|
||||
for (let i = 0; i < parsed.length; i++) {
|
||||
const l = parsed[i];
|
||||
if (!l || !isSecretLine(l)) continue;
|
||||
const old = now.get(idOf(l));
|
||||
if (l.value === agent.FRP_HIDDEN) {
|
||||
if (!old) return { ok: false, message: `${nameOf(l)} shows ${agent.FRP_HIDDEN}, but the file on the server has no value for it there. Secrets are set on the server.` };
|
||||
src[i] = src[i]!.slice(0, l.start) + old.raw + src[i]!.slice(l.end);
|
||||
} else if (l.value && (!old || old.value !== l.value)) {
|
||||
return { ok: false, message: `${nameOf(l)} is a secret: it can't be set or changed from the Hub. Change it on the server.` };
|
||||
}
|
||||
}
|
||||
return { ok: true, content: src.join("\n") };
|
||||
}
|
||||
|
||||
// ─── Read, write ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** systemd's view of a unit: true / false, or null when there's no systemctl. */
|
||||
export async function serviceActive(unit: string): Promise<boolean | null> {
|
||||
const r = await execText("systemctl", ["is-active", unit]);
|
||||
if (r.missing) return null;
|
||||
return r.out.trim() === "active";
|
||||
}
|
||||
|
||||
export interface FrpDeps {
|
||||
/** For tests: systemctl and `frp* verify`. */
|
||||
exec?: (cmd: string, args: string[]) => Promise<{ ok: boolean; out: string; err: string; missing: boolean }>;
|
||||
wait?: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
export async function readConfig(mode: agent.AgentMode, opts: { path?: string } = {}, deps: FrpDeps = {}): Promise<agent.FrpReadResult> {
|
||||
const service = serviceFor(mode);
|
||||
if (opts.path) {
|
||||
if (exists(opts.path)) rememberPath(opts.path);
|
||||
forgetFound();
|
||||
}
|
||||
const found = opts.path ? { ...(await findConfig(mode, { fresh: true })), ...(exists(opts.path) ? {} : { path: opts.path, source: "hub" as const }) } : await findConfig(mode, { fresh: true });
|
||||
const exec = deps.exec ?? execText;
|
||||
const running = await (async () => { const r = await exec("systemctl", ["is-active", service]); return r.missing ? null : r.out.trim() === "active"; })();
|
||||
const base = { service, path: found.path, source: found.source, serviceRunning: running, readAt: new Date().toISOString() };
|
||||
let text: string | null = null;
|
||||
if (found.path) {
|
||||
try {
|
||||
const st = fs.statSync(found.path);
|
||||
if (st.size > agent.FRP_CONFIG_MAX) throw new Error(`${found.path} is ${st.size} bytes; the Hub shows files up to ${agent.FRP_CONFIG_MAX}.`);
|
||||
text = fs.readFileSync(found.path, "utf8");
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||
}
|
||||
}
|
||||
if (text === null) {
|
||||
return { ...base, found: false, format: null, content: null, hidden: [], proxyBindAddr: null, allowPorts: null, looked: found.path ? [found.path] : found.looked };
|
||||
}
|
||||
const format = formatOf(found.path!, text);
|
||||
const settings = parseSettings(text, format);
|
||||
const { content, hidden } = hideSecrets(text, format);
|
||||
return {
|
||||
...base, found: true, format, content, hidden,
|
||||
proxyBindAddr: service === "frps" ? settings.proxyBindAddr : null,
|
||||
allowPorts: service === "frps" ? settings.allowPorts : null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface WriteOutcome {
|
||||
status: agent.JobStatus;
|
||||
message?: string;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
|
||||
|
||||
export async function writeConfig(mode: agent.AgentMode, args: { path: string; content: string; restart: boolean }, deps: FrpDeps = {}): Promise<WriteOutcome> {
|
||||
const exec = deps.exec ?? execText;
|
||||
const wait = deps.wait ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const service = serviceFor(mode);
|
||||
const steps: agent.ReportStep[] = [];
|
||||
const step = (name: string, outcome: agent.ReportStep["outcome"], detail?: string) => {
|
||||
const at = new Date().toISOString();
|
||||
steps.push({ name, startedAt: at, finishedAt: at, outcome, ...(detail ? { detail: detail.slice(0, 2000) } : {}) });
|
||||
};
|
||||
const refuse = (message: string): WriteOutcome => ({ status: "refused", message, steps, result: {} });
|
||||
|
||||
const found = await findConfig(mode, { fresh: true });
|
||||
if (found.path !== args.path) return refuse(`This server's ${service} config is ${found.path ?? "not found"}, not ${args.path}. Read it again on the Hub first.`);
|
||||
if (!path.basename(args.path).startsWith(service)) return refuse(`${args.path} isn't ${service}'s config (the name must start with ${service}).`);
|
||||
let current: string;
|
||||
try { current = fs.readFileSync(args.path, "utf8"); } catch { return refuse(`There's no file at ${args.path} to replace.`); }
|
||||
const format = formatOf(args.path, current);
|
||||
const restored = restoreSecrets(args.content.replace(/\r\n/g, "\n"), current, format);
|
||||
if (!restored.ok) return refuse(restored.message);
|
||||
const next = restored.content.endsWith("\n") ? restored.content : `${restored.content}\n`;
|
||||
if (next === current) {
|
||||
step("Compare", "skipped", "The file is already like this; nothing changed.");
|
||||
return { status: "succeeded", message: "Nothing changed: the file is already like this.", steps, result: await readConfig(mode, {}, deps) as unknown as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const dir = path.dirname(args.path);
|
||||
const tmp = path.join(dir, `.${path.basename(args.path)}.crosscode-${process.pid}${path.extname(args.path)}`);
|
||||
const mode0 = fs.statSync(args.path).mode & 0o777;
|
||||
fs.writeFileSync(tmp, next, { mode: mode0 });
|
||||
try {
|
||||
const v = await exec(found.bin, ["verify", "-c", tmp]);
|
||||
if (v.missing) { step(`${service} verify`, "failed", `${found.bin} wasn't found.`); return { status: "failed", message: `${found.bin} wasn't found, so the new config couldn't be checked; nothing changed.`, steps, result: {} }; }
|
||||
if (!v.ok) { step(`${service} verify`, "failed", `${v.out}\n${v.err}`.trim()); return { status: "failed", message: `${service} verify refused the new config, so nothing changed: ${(v.err || v.out).trim().slice(0, 500)}`, steps, result: {} }; }
|
||||
step(`${service} verify`, "ok");
|
||||
} catch (e) {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
throw e;
|
||||
}
|
||||
|
||||
const backups = path.join(dir, "backups");
|
||||
fs.mkdirSync(backups, { recursive: true, mode: 0o700 });
|
||||
const backup = path.join(backups, `${path.basename(args.path)}.${stamp()}`);
|
||||
fs.copyFileSync(args.path, backup);
|
||||
fs.chmodSync(backup, mode0);
|
||||
fs.renameSync(tmp, args.path);
|
||||
step("Replace the config", "ok", `Backup: ${backup}`);
|
||||
|
||||
if (!args.restart) {
|
||||
step(`Restart ${service}`, "skipped", "Not asked: the new config is used when frp next starts.");
|
||||
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
|
||||
}
|
||||
const restart = await exec("systemctl", ["restart", service]);
|
||||
await wait(3000);
|
||||
const up = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
|
||||
if (restart.ok && up) {
|
||||
step(`Restart ${service}`, "ok");
|
||||
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
|
||||
}
|
||||
step(`Restart ${service}`, "failed", restart.err || `${service} isn't running after the restart.`);
|
||||
fs.copyFileSync(backup, args.path);
|
||||
await exec("systemctl", ["restart", service]);
|
||||
await wait(3000);
|
||||
const back = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
|
||||
step("Put the old config back", back ? "rolled-back" : "failed", back ? `${service} runs with the old config again.` : `${service} isn't running with the old config either: look at it on the server (journalctl -u ${service}).`);
|
||||
return {
|
||||
status: back ? "rolled-back" : "failed",
|
||||
message: back ? `${service} didn't start with the new config, so the old one was put back.` : `${service} didn't start with the new config, and isn't running after putting the old one back either.`,
|
||||
steps,
|
||||
result: { ...(await readConfig(mode, {}, deps)), backup },
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Free ports (probe-ports) ─────────────────────────────────────────────────
|
||||
|
||||
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
|
||||
export function portAllowed(port: number, allowPorts: string | null): boolean {
|
||||
if (!allowPorts) return true;
|
||||
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
|
||||
const [a, b] = range.split("-").map((n) => Number(n.trim()));
|
||||
if (!Number.isFinite(a)) return false;
|
||||
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
|
||||
});
|
||||
}
|
||||
|
||||
export function probePorts(ports: number[], mode: agent.AgentMode, settings: FrpSettings | null, listening: Map<number, string[]>, configPath: string | null): agent.ProbePortsResult {
|
||||
const used = new Set(settings?.usedPorts ?? []);
|
||||
return {
|
||||
configPath,
|
||||
ports: ports.map((port) => {
|
||||
const addrs = listening.get(port);
|
||||
if (addrs?.length) return { port, free: false, reason: `In use: something listens on ${[...new Set(addrs)].join(", ")}.` };
|
||||
if (mode === "central" && settings && !portAllowed(port, settings.allowPorts)) return { port, free: false, reason: "Not in frps's allow_ports." };
|
||||
if (used.has(port)) return { port, free: false, reason: `Used in ${mode === "central" ? "frps" : "frpc"}'s config.` };
|
||||
return { port, free: true, reason: null };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings of the config this server uses, or null when there's none. */
|
||||
export async function currentSettings(mode: agent.AgentMode): Promise<{ path: string | null; settings: FrpSettings | null }> {
|
||||
const found = await findConfig(mode);
|
||||
if (!found.path) return { path: null, settings: null };
|
||||
try {
|
||||
const text = fs.readFileSync(found.path, "utf8");
|
||||
return { path: found.path, settings: parseSettings(text, formatOf(found.path, text)) };
|
||||
} catch {
|
||||
return { path: found.path, settings: null };
|
||||
}
|
||||
}
|
||||
+23
-3
@@ -2,7 +2,8 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { encryptExport } from "@crosscode/contracts/signing";
|
||||
import { checkPorts, listeningNow, readFrps } from "./central";
|
||||
import { checkPorts, listeningNow } from "./central";
|
||||
import { currentSettings, findConfig, probePorts, readConfig, writeConfig } from "./frp";
|
||||
import { crosscodeArgs } from "./command";
|
||||
import type { AgentConfig, Keys } from "./config";
|
||||
import { type HubClient, HubRequestError } from "./hub";
|
||||
@@ -153,10 +154,25 @@ export class Agent {
|
||||
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
|
||||
}
|
||||
case "check-ports": {
|
||||
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
|
||||
const { path: configPath, settings } = await currentSettings("central");
|
||||
const res = checkPorts(job.args.ports, settings, await listeningNow(), configPath);
|
||||
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
|
||||
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "frp-read": {
|
||||
const result = await readConfig(this.deps.config.mode, { path: job.args.path });
|
||||
const message = result.found ? undefined : `No ${result.service} config found${result.path ? ` at ${result.path}` : ""}.`;
|
||||
return { status: result.found ? "succeeded" : "failed", steps: [], result: result as unknown as Record<string, unknown>, message, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "frp-write": {
|
||||
const w = await writeConfig(this.deps.config.mode, job.args);
|
||||
return { status: w.status, steps: w.steps, result: w.result, message: w.message, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "probe-ports": {
|
||||
const { path: configPath, settings } = await currentSettings(this.deps.config.mode);
|
||||
const result = probePorts(job.args.ports, this.deps.config.mode, settings, await listeningNow(), configPath);
|
||||
return { status: "succeeded", steps: [], result: result as unknown as Record<string, unknown>, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "export":
|
||||
return await this.runExport(job, limit);
|
||||
case "status":
|
||||
@@ -181,7 +197,11 @@ export class Agent {
|
||||
|
||||
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
|
||||
if (this.deps.run) return this.deps.run(args, job);
|
||||
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
|
||||
return (async () => {
|
||||
// crosscode edits frpc's config on installs: tell it where the file is (agent 1.4.0).
|
||||
const frpc = this.deps.config.mode === "church" ? (await findConfig("church").catch(() => null))?.path : null;
|
||||
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit, env: frpc ? { FRPC_INI: frpc } : {} });
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,8 +15,6 @@ export const paths = {
|
||||
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
|
||||
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
|
||||
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
|
||||
/** frps.ini on the central server. */
|
||||
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
|
||||
/** The churches on a church server. */
|
||||
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
|
||||
};
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface RunOptions {
|
||||
sealedConfig?: agent.Sealed | null;
|
||||
x25519Pem: string;
|
||||
timeLimitMinutes: number;
|
||||
/** Extra environment for crosscode (FRPC_INI). */
|
||||
env?: Record<string, string>;
|
||||
/** For tests. */
|
||||
bin?: string;
|
||||
}
|
||||
@@ -59,7 +61,7 @@ export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
|
||||
const child = spawn(opts.bin ?? paths.crosscode, args, {
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
|
||||
env: { ...process.env, ...opts.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
|
||||
});
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { readFrps } from "./central";
|
||||
import { currentSettings, serviceActive } from "./frp";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
@@ -12,7 +12,7 @@ import { paths } from "./paths";
|
||||
* the tools that are there; anything missing is null rather than an error.
|
||||
*/
|
||||
|
||||
export const AGENT_VERSION = "1.2.0";
|
||||
export const AGENT_VERSION = "1.7.0";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
@@ -159,9 +159,10 @@ export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentSt
|
||||
frpcRunning,
|
||||
processes,
|
||||
};
|
||||
const frp = await currentSettings(mode).catch(() => ({ path: null, settings: null }));
|
||||
stats.frpConfigPath = frp.path;
|
||||
if (mode === "central") {
|
||||
const frps = readFrps();
|
||||
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
|
||||
stats.central = { proxyBindAddr: frp.settings?.proxyBindAddr ?? null, allowPorts: frp.settings?.allowPorts ?? null, frpsRunning: await serviceActive("frps") };
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,10 @@ describe("crosscode arguments for each job", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
|
||||
// 1.5.0: one product of the church.
|
||||
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope", products: ["events"] } }))).toEqual(["uninstall", "hope", "events", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope", products: ["events"] } }))).toEqual(["purge", "hope", "events", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh", products: ["accounts"] } }), { exportFile: "/x/e.zip" })).toEqual(["export", "hope", "accounts", "--out", "/x/e.zip"]);
|
||||
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
|
||||
});
|
||||
|
||||
@@ -43,6 +47,38 @@ describe("crosscode arguments for each job", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "ministry" } }))).toEqual(["demo", "hope", "--profile", "ministry"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", profile: "events", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "hope", "--profile", "events", "--admin-email", "jane@hope.test"]);
|
||||
// 1.6.0: the Website's demo.
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant" } }))).toEqual(["demo", "hope", "website", "--profile", "bold-plant"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "small" } }))).toEqual(["demo", "hope", "--profile", "small"]);
|
||||
});
|
||||
|
||||
it("seed-scenario 1.7.0: one job, no product named, so the server seeds whatever the church has", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "community-family" } }))).toEqual(["demo", "demo2", "--scenario", "community-family"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "demo2", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
|
||||
expect(() => parsed({ type: "seed-scenario", args: { church: "demo2", scenario: "bold-youth", products: ["website"] } })).toThrow();
|
||||
});
|
||||
|
||||
it("seed-demo 1.7.0: the App's and Accounts' demos, and a scenario passed on to every product", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "app", profile: "community-family" } }))).toEqual(["demo", "hope", "app", "--profile", "community-family"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "accounts", profile: "bold-youth", scenario: "bold-youth" } })))
|
||||
.toEqual(["demo", "hope", "accounts", "--profile", "bold-youth", "--scenario", "bold-youth"]);
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "clean-campus", scenario: "clean-campus" } })))
|
||||
.toEqual(["demo", "hope", "website", "--profile", "clean-campus", "--scenario", "clean-campus"]);
|
||||
// Events keeps its old form (no product), with the scenario and the admin kept.
|
||||
expect(crosscodeArgs(parsed({ type: "seed-demo", args: { church: "hope", product: "events", profile: "bold-youth", scenario: "bold-youth", adminEmail: "jane@hope.test" } })))
|
||||
.toEqual(["demo", "hope", "--profile", "bold-youth", "--scenario", "bold-youth", "--admin-email", "jane@hope.test"]);
|
||||
// A scenario's profile must be the scenario's for that product (the contracts refuse the job).
|
||||
expect(() => parsed({ type: "seed-demo", args: { church: "hope", product: "website", profile: "bold-plant", scenario: "bold-youth" } })).toThrow();
|
||||
});
|
||||
|
||||
it("env-read and env-set (1.3.0): crosscode env, each value its own argument", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "env-read", args: { church: "hope", product: "accounts" } }))).toEqual(["env", "hope", "accounts"]);
|
||||
expect(crosscodeArgs(parsed({
|
||||
type: "env-set",
|
||||
args: { church: "hope", product: "events", file: "backend/.env", set: { FRONTEND_URL: "https://events.hope.co.za", ORG_NAME: "Hope; rm -rf /" }, unset: ["OLD"], restart: true },
|
||||
}))).toEqual(["env", "hope", "events", "--file", "backend/.env", "--set", "FRONTEND_URL=https://events.hope.co.za", "--set", "ORG_NAME=Hope; rm -rf /", "--unset", "OLD", "--restart"]);
|
||||
expect(() => parsed({ type: "env-set", args: { church: "hope", product: "events", file: "backend/.env", set: { JWT_SECRET: "x" }, unset: [], restart: false } })).toThrow();
|
||||
});
|
||||
|
||||
it("export writes to the file the agent gives", () => {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import {
|
||||
configFromCommand, findConfig, forgetFound, hideSecrets, parseExecStart, parseSettings, probePorts, readConfig, restoreSecrets, writeConfig,
|
||||
} from "../src/frp";
|
||||
import { tempState } from "./helpers";
|
||||
|
||||
const H = agent.FRP_HIDDEN;
|
||||
|
||||
const TOML = `bindPort = 7000
|
||||
proxyBindAddr = "127.0.0.1"
|
||||
auth.token = "s3cret-token" # the shared token
|
||||
allowPorts = [
|
||||
{ start = 20000, end = 29999 },
|
||||
{ single = 3001 },
|
||||
]
|
||||
|
||||
[webServer]
|
||||
port = 7500
|
||||
password = 'dash-pass'
|
||||
`;
|
||||
|
||||
const FRPC_INI = `[common]
|
||||
server_addr = 203.0.113.10
|
||||
server_port = 7000
|
||||
token = abc123
|
||||
|
||||
[hope-events-web]
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 20010
|
||||
remote_port = 20010
|
||||
`;
|
||||
|
||||
const noSystemd = async () => ({ ok: false, out: "", err: "", missing: true });
|
||||
|
||||
describe("finding frp's config", () => {
|
||||
it("reads -c from the systemd unit", () => {
|
||||
expect(configFromCommand("/usr/local/bin/frps -c /usr/local/frp/frps.toml")).toBe("/usr/local/frp/frps.toml");
|
||||
expect(configFromCommand("/usr/bin/frps --config=/etc/frps/frps.ini")).toBe("/etc/frps/frps.ini");
|
||||
expect(configFromCommand("/usr/bin/frps")).toBeNull();
|
||||
expect(parseExecStart("{ path=/usr/local/bin/frps ; argv[]=/usr/local/bin/frps -c /opt/frp/frps.toml ; ignore_errors=no ; start_time=[n/a] }"))
|
||||
.toEqual({ config: "/opt/frp/frps.toml", bin: "/usr/local/bin/frps" });
|
||||
});
|
||||
|
||||
it("the path from the Hub wins, and is remembered", async () => {
|
||||
const dir = tempState();
|
||||
const file = path.join(dir, "frps.toml");
|
||||
fs.writeFileSync(file, TOML);
|
||||
forgetFound();
|
||||
const exec = async () => ({ ok: true, out: "active\n", err: "", missing: false });
|
||||
const r = await readConfig("central", { path: file }, { exec });
|
||||
expect(r).toMatchObject({ found: true, source: "hub", path: file, format: "toml", proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001", serviceRunning: true });
|
||||
forgetFound();
|
||||
expect((await findConfig("central", { fresh: true })).path).toBe(file);
|
||||
});
|
||||
|
||||
it("a path that isn't there is reported, not remembered", async () => {
|
||||
const dir = tempState();
|
||||
forgetFound();
|
||||
const r = await readConfig("central", { path: path.join(dir, "nope", "frps.ini") }, { exec: noSystemd });
|
||||
expect(r).toMatchObject({ found: false, content: null });
|
||||
expect(fs.existsSync(path.join(dir, "frp.json"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("frp settings, INI and TOML", () => {
|
||||
it("TOML", () => {
|
||||
expect(parseSettings(TOML, "toml")).toMatchObject({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001" });
|
||||
expect(parseSettings(TOML, "toml").usedPorts).toEqual(expect.arrayContaining([7000, 7500]));
|
||||
});
|
||||
it("INI: frpc's tunnels use their ports", () => {
|
||||
expect(parseSettings(FRPC_INI, "ini").usedPorts).toEqual([20010]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("secrets never leave the server", () => {
|
||||
it("are hidden in TOML and INI, keeping the quotes", () => {
|
||||
const t = hideSecrets(TOML, "toml");
|
||||
expect(t.content).toContain(`auth.token = "${H}" # the shared token`);
|
||||
expect(t.content).toContain(`password = '${H}'`);
|
||||
expect(t.content).not.toMatch(/s3cret|dash-pass/);
|
||||
expect(t.hidden).toEqual(["auth.token", "webServer.password"]);
|
||||
const i = hideSecrets(FRPC_INI, "ini");
|
||||
expect(i.content).toContain(`token = ${H}`);
|
||||
expect(i.content).not.toContain("abc123");
|
||||
});
|
||||
it("in inline tables too", () => {
|
||||
expect(hideSecrets(`auth = { method = "token", token = "zzz" }\n`, "toml").content).not.toContain("zzz");
|
||||
});
|
||||
it("are put back on write, and can't be changed from the Hub", () => {
|
||||
const shown = hideSecrets(TOML, "toml").content.replace("bindPort = 7000", "bindPort = 7001");
|
||||
const back = restoreSecrets(shown, TOML, "toml");
|
||||
expect(back.ok && back.content).toBe(TOML.replace("bindPort = 7000", "bindPort = 7001"));
|
||||
expect(restoreSecrets(shown.replace(`"${H}"`, '"new"'), TOML, "toml")).toMatchObject({ ok: false, message: expect.stringMatching(/auth.token is a secret/) });
|
||||
expect(restoreSecrets(`${shown}\n[extra]\ntoken = "${H}"\n`, TOML, "toml")).toMatchObject({ ok: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("writing the config", () => {
|
||||
const setup = () => {
|
||||
const dir = tempState();
|
||||
const file = path.join(dir, "frps.toml");
|
||||
fs.writeFileSync(file, TOML);
|
||||
fs.writeFileSync(path.join(dir, "frp.json"), JSON.stringify({ path: file }));
|
||||
forgetFound();
|
||||
return { dir, file };
|
||||
};
|
||||
const shown = () => hideSecrets(TOML, "toml").content;
|
||||
|
||||
it("verify, backup, replace, restart", async () => {
|
||||
const { dir, file } = setup();
|
||||
const calls: string[] = [];
|
||||
const exec = async (cmd: string, args: string[]) => { calls.push(`${cmd} ${args.join(" ")}`); return { ok: true, out: "active", err: "", missing: false }; };
|
||||
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
|
||||
expect(r.status).toBe("succeeded");
|
||||
expect(fs.readFileSync(file, "utf8")).toContain("bindPort = 7001");
|
||||
expect(fs.readFileSync(file, "utf8")).toContain("s3cret-token");
|
||||
expect(fs.readdirSync(path.join(dir, "backups"))).toHaveLength(1);
|
||||
expect(calls.some((c) => / verify -c /.test(c))).toBe(true);
|
||||
expect(calls).toContain("systemctl restart frps");
|
||||
expect(JSON.stringify(r.result)).not.toContain("s3cret");
|
||||
});
|
||||
|
||||
it("verify refuses: nothing changes", async () => {
|
||||
const { file } = setup();
|
||||
const exec = async (cmd: string) => ({ ok: cmd === "systemctl", out: "", err: "bad key", missing: false });
|
||||
const r = await writeConfig("central", { path: file, content: "nonsense = [", restart: true }, { exec, wait: async () => {} });
|
||||
expect(r.status).toBe("failed");
|
||||
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
|
||||
});
|
||||
|
||||
it("frps doesn't come back: the old file is put back", async () => {
|
||||
const { file } = setup();
|
||||
let restarts = 0;
|
||||
const exec = async (_cmd: string, args: string[]) => {
|
||||
if (args[0] === "restart") restarts++;
|
||||
if (args[0] === "is-active") return { ok: true, out: restarts >= 2 ? "active" : "failed", err: "", missing: false };
|
||||
return { ok: true, out: "", err: "", missing: false };
|
||||
};
|
||||
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
|
||||
expect(r.status).toBe("rolled-back");
|
||||
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
|
||||
});
|
||||
|
||||
it("only the file the agent uses", async () => {
|
||||
const { dir } = setup();
|
||||
const r = await writeConfig("central", { path: path.join(dir, "frpc.toml"), content: "x = 1", restart: false }, { exec: noSystemd });
|
||||
expect(r.status).toBe("refused");
|
||||
});
|
||||
});
|
||||
|
||||
describe("free ports before an install", () => {
|
||||
it("central: not listening and inside allow_ports", () => {
|
||||
const listening = new Map([[20001, ["0.0.0.0"]]]);
|
||||
const r = probePorts([20000, 20001, 30000], "central", parseSettings(TOML, "toml"), listening, "/etc/frp/frps.toml");
|
||||
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20000, true], [20001, false], [30000, false]]);
|
||||
});
|
||||
it("church: not listening and not in frpc's tunnels", () => {
|
||||
const r = probePorts([20010, 20011], "church", parseSettings(FRPC_INI, "ini"), new Map(), "/etc/frp/frpc.ini");
|
||||
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20010, false], [20011, true]]);
|
||||
});
|
||||
it("with no config found, listening is all it can check", () => {
|
||||
expect(probePorts([20010], "central", null, new Map(), null).ports[0]!.free).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,225 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.8.0] - 2026-11-30
|
||||
|
||||
Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on
|
||||
`main` builds it). **One migration** (`20261130120000_whatsapp_stop`): `User.whatsappOptedOut` and a
|
||||
`WhatsAppStop` table. No new settings. Works with any Accounts; the opt-out reaches the church's
|
||||
other products with Accounts 1.9.0. Part of Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
|
||||
|
||||
### Changed
|
||||
|
||||
- **STOP stops all WhatsApp** (APP-1.0-PLAN decision 11), not only news: event updates, tickets,
|
||||
kids check-in messages and two-step codes too (codes go by email). Checked before every message
|
||||
(`sendText`, `sendPdf`, `src/utils/whatsappStop.js`), against the numbers that replied STOP here
|
||||
(`WhatsAppStop`) and the accounts Accounts says opted out (`User.whatsappOptedOut`, from
|
||||
`user.updated`'s `whatsapp_opted_out`). News on WhatsApp is turned off as before.
|
||||
- **A STOP received here is passed on to Accounts** (`whatsapp.optout`, contracts 1.20.0), which
|
||||
keeps it for every product. The reply says how to undo it: the account page in Accounts, or,
|
||||
without Accounts, reply START (which turns it back on here). With Accounts, START only answers
|
||||
with the account page; turned back on there, `user.updated` clears this site's STOP for the
|
||||
number too. STOPP and UITTEKEN (Afrikaans) count as STOP.
|
||||
|
||||
### Added
|
||||
|
||||
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12): `set-demo.js --profile=<scenario>` for
|
||||
the eight (heritage-parish … clean-campus), each built as one of the four kinds of demo but around
|
||||
the scenario's church from `@crosscode/demo`: its people (the same as in Accounts, the Website and
|
||||
the App; leads become the demo staff and event contacts), and its own campuses with people at
|
||||
their home campus. Accounts' part loads first; the demo then links its people to their accounts
|
||||
and never removes them (`people.removeDemo` skips the scenario's own). A small church's events
|
||||
sell to the people it has (the breakfast isn't sold out at St Columba's). The four demos as before.
|
||||
|
||||
## [3.7.2] - 2026-11-27
|
||||
|
||||
No migrations, no new settings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **New demo data no longer leaves the old events on the church's Website.** `set-demo.js`
|
||||
truncated `FeedEntry`, so the feed never listed the old events in `deleted` and the Website kept
|
||||
showing them beside the new ones. Now `FeedEntry` is kept and its live entries are marked removed,
|
||||
the links' `lastGoodAt` is reset (their copies were truncated, so the next fetch is a full one),
|
||||
and after loading the script publishes the new events, sends `event.changed` to the linked
|
||||
products and fetches their events back in (`demoFeed`), so the Website's next page load is right.
|
||||
- **Copies of a linked product's events can't stay forever.** The 15-minute `feed-sync` job and
|
||||
"Sync now" fetch the whole list and drop copies that aren't in it (`syncLink(link, now, { full: true })`),
|
||||
so events a sibling lost without listing them in `deleted` (a reseed, a restore) go within 15
|
||||
minutes. The fetch after an `event.changed` still asks only for what changed.
|
||||
|
||||
## [3.7.1] - 2026-11-26
|
||||
|
||||
No migrations, no new settings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A product installed after this site's last heartbeat can connect straight away.** A connect
|
||||
(in either direction) was refused while the other install wasn't in the cached copy of the Hub's
|
||||
list, refreshed every 15 minutes. So a new Church Website couldn't connect for the event feed
|
||||
until then. Now, for an install it doesn't know, the site sends the Hub a heartbeat to get a fresh
|
||||
list and looks again (at most one such heartbeat a minute, so unknown installs can't make it call
|
||||
the Hub more often). Same change as Accounts 1.7.1 and Website 1.0.2.
|
||||
|
||||
## [3.7.0] - 2026-11-24
|
||||
|
||||
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). **Requires Accounts 1.7.0**
|
||||
(WHATS-NEW.md says so, and the Hub updates Accounts first) for the brand style. No migrations, no
|
||||
new settings.
|
||||
|
||||
### Added
|
||||
|
||||
- **The church's fonts and corners on the public pages.** The backend reads the church profile from
|
||||
Accounts (`GET /api/church/v1`, kept for 10 minutes; `src/accounts/church.ts`) and the public
|
||||
pages get it from the new `GET /api/v2/church` (public). `<html>` gets `brandAttributes(style)`
|
||||
from `@crosscode/ui` and the root layout imports `@crosscode/ui/fonts.css` (self-hosted, so no
|
||||
font is loaded from another site). Body text and h1–h3 use `--cc-font-body` and
|
||||
`--cc-font-heading` when the church picked a pairing, and `--radius` follows the corner style
|
||||
(`soft` is 0.5rem, the same as before). The dashboard and setup screens (`data-cc-staff`) keep
|
||||
the system fonts and 0.5rem.
|
||||
- **`church.changed` from Accounts** at `POST /api/church/v1/changed` (signed with the Accounts
|
||||
link, `LINK_HEADERS`): the profile is fetched again on the next page. Before 3.7.0 this answered
|
||||
404 and Accounts kept retrying for a week.
|
||||
- **The shared church footer** (`ChurchFooter`, `@crosscode/ui` 0.3.0) on the public pages when
|
||||
Accounts is connected: name and logo, service times, address, contact, social links and links
|
||||
to the church's other sites and the privacy notice, with Terms of Use and cookie settings below.
|
||||
Without Accounts, and on the dashboard (`<Footer plain />`), the footer is as before.
|
||||
- **Links to the church's other sites** in the header of the public pages (its Website, later its
|
||||
App), from the profile's `links`.
|
||||
|
||||
### Changed
|
||||
|
||||
- `@crosscode/ui` 0.3.0: `ChurchFooter` takes `bottom` (a product's own links after the copyright).
|
||||
- Frontend: `transpilePackages: ["@crosscode/ui"]`; Tailwind scans `packages/ui/src` and has
|
||||
`brand` (brand-700) for the shared footer.
|
||||
|
||||
## [3.6.1] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Uploading a logo or favicon under Settings → Branding failed on some servers** with "The logo was
|
||||
uploaded, but the site can't show it yet". The upload worked, but on a server whose proxy has a
|
||||
rule for file extensions (static-file caching) every `/api/…` path ending in `.png`, `.ico`,
|
||||
`.pdf`, `.json` and so on went to the site (Next.js), which answered 404. So the check after the
|
||||
upload failed, as did pictures, certificate PDFs and `/api/v2/openapi.json`. Two changes:
|
||||
- The site passes `/api/*` and `/uploads/*` that reach it on to the backend
|
||||
(`next.config.ts` rewrites, `beforeFiles`). New frontend setting `BACKEND_INTERNAL_URL`
|
||||
(`http://127.0.0.1:<apiPort>`, added to `.env.production` on deploy). Unset, nothing is
|
||||
passed on, as before. The end-to-end tests' `E2E_API_PROXY` uses the same rewrites.
|
||||
- The nginx site the installers write (and DEPLOYMENT.md) sends `/api/` and `/uploads/` to the
|
||||
backend with `location ^~`, so no regex location can take them. Existing servers keep their
|
||||
nginx file: change it by hand (DEPLOYMENT.md §4).
|
||||
|
||||
## [3.6.0] - 2026-11-20
|
||||
|
||||
Works with any Accounts; the people check needs Accounts 1.5.0 (with an older one it's skipped).
|
||||
|
||||
### Added
|
||||
|
||||
- **The nightly people check** (`accounts-people-check`, 04:30, `ACCOUNTS_PEOPLE_CHECK_ENABLED`,
|
||||
`src/accounts/peopleCheck.ts`). In Accounts mode it sends every linked person's `sub` to
|
||||
Accounts, 500 at a time (`people.check`, contracts 1.14.0), and: updates the local copy where the
|
||||
name, email, phone or news choices differ (as `user.updated`); handles deleted accounts as
|
||||
`user.deleted` (anonymised, or deferred while there's a registration for an event that hasn't
|
||||
ended); counts deactivated and unknown people. When more than half a page (10+) is unknown, the
|
||||
site is probably linked to the wrong Accounts: the check stops, changes nothing for them, fails
|
||||
(Background jobs, the Hub's "jobs failing") and records why (the Hub's "sign-in failed" alert).
|
||||
|
||||
## [3.5.0] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- **After "Load demo data" nobody could sign in** ("Sign-in isn't available right now",
|
||||
`ACCOUNTS_UNAVAILABLE`). `scripts/set-demo.js` emptied `ProductLink` (it keeps only a few tables)
|
||||
but kept `AppSetting`, so the site stayed in Accounts mode with no Accounts link, and
|
||||
`accounts_auto_connected` stopped it reconnecting. Demo data now keeps `ProductLink` and
|
||||
`LinkNonce`, and a site in Accounts mode without a link connects to the Accounts the Hub lists at
|
||||
its next heartbeat whatever happened before (a site on its own sign-in still keeps an admin's
|
||||
Disconnect).
|
||||
|
||||
### Added
|
||||
|
||||
- Heartbeat `stats.signIn` (contracts 1.13.0): the sign-in mode, the linked Accounts (install id and
|
||||
address) and the last failure to start or finish a sign-in (`accounts_last_signin_error`, cleared
|
||||
by the next sign-in that works). The Hub 2.9.0 alerts on it.
|
||||
|
||||
## [3.4.0] - 2026-11-20
|
||||
|
||||
### Added
|
||||
|
||||
- **Background jobs are switched on and off from Settings → Background jobs.** Each job has a
|
||||
switch and a Schedule button (presets or a cron expression). The choice is saved in the database
|
||||
(`AppSetting` `job_overrides`), wins over the .env (the job's own flag such as
|
||||
`WAITLIST_JOB_ENABLED`, and `JOB_SCHEDULE_<NAME>`), and applies straight away: the queue is
|
||||
rescheduled in this process, and other processes see it within 30 seconds (a run of a job switched
|
||||
off elsewhere is skipped). "use the .env" goes back to what the server says.
|
||||
`JOBS_ENABLED=false` still turns every job off (the end-to-end tests use it).
|
||||
API: `PUT /api/v2/admin/jobs/:name` `{ enabled, cron }` (null goes back to the .env); `GET
|
||||
/admin/jobs` also gives `envEnabled`, `envCron`, `defaultCron` and `override`.
|
||||
|
||||
### Changed
|
||||
|
||||
- "Run now" also works for a job that's switched off.
|
||||
|
||||
## [3.3.0] - 2026-11-20
|
||||
|
||||
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
|
||||
just stay there).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **An uploaded logo or favicon could point at a file that "didn't exist".** Uploads were saved in
|
||||
`backend/public/uploads` but served from `public/uploads` under whatever folder the backend
|
||||
was started from, so a backend started elsewhere answered 404 for a logo it had just saved. Both
|
||||
now use one folder (`src/utils/uploads.js`); logos saved before the fix show again. Settings →
|
||||
Branding also checks the new file loads before saving it, and says why an upload failed.
|
||||
- **Signing out didn't sign out of Accounts.** The navbar and bottom bar loaded the home page
|
||||
straight after starting the sign-out call, which cancelled it. `logout()` now waits for it, then
|
||||
goes to Accounts' sign-out (and back) itself.
|
||||
|
||||
### Changed
|
||||
|
||||
- **New demo data replaces the old demo people in Accounts too** (`set-demo`, `crosscode demo`,
|
||||
the Hub's Load demo data): the last demo's people are removed there first (contracts 1.11.0
|
||||
`people.removeDemo`, `src/accounts/move.ts removeDemoPeople`), then the new ones moved in.
|
||||
|
||||
## [3.2.0] - 2026-11-19
|
||||
|
||||
### Added
|
||||
|
||||
- **The heartbeat says what's on now** (`stats.live`, contracts 1.10.0, `hub/report.js liveNow`):
|
||||
events with a session on now, or a one-day event (no sessions, at most 36 hours) on now, each give
|
||||
or take 30 minutes, and tickets checked in during the last hour. Hub 2.7.0 asks for a second "yes"
|
||||
before an emergency update takes a site with an event on down.
|
||||
|
||||
## [3.1.0] - 2026-11-19
|
||||
|
||||
Found after a church moved sign-in without email set up in Accounts: Accounts couldn't send codes or
|
||||
password links, sign-in failed with a 500, and nobody could get in. Requires Accounts 1.2.0
|
||||
(`— requires accounts 1.2.0`) and contracts 1.9.0.
|
||||
|
||||
### Added
|
||||
|
||||
- **Settings → Sign-in → Email and WhatsApp for the church's sign-in** (`src/accounts/messaging.ts`,
|
||||
`components/admin/AccountsMessaging.tsx`): what Accounts can send, and this site's SMTP and WAWP
|
||||
settings to copy into it. The password and access token never reach the page: left blank, this
|
||||
site's own are used, sealed with the link's secret on the way. **Send a test** has Accounts send a
|
||||
test email / WhatsApp with those settings (nothing saved); **Save in Accounts** tests again and
|
||||
saves each part only if its test worked. Shown whenever Accounts is connected, so a church that
|
||||
already moved can mend it. `GET /api/v2/settings/sign-in/messaging`, `POST …/messaging/test`,
|
||||
`POST …/messaging`.
|
||||
|
||||
- **"Use this site's logo and colours"** on Settings → Sign-in (`POST /api/v2/settings/sign-in/look`):
|
||||
the church's sign-in pages get this site's name, logo (made a full address) and colours
|
||||
(`church.branding`); a move sends them too, filling only what Accounts doesn't have
|
||||
(`src/accounts/look.ts`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The move needs Accounts' email.** Check reports what Accounts can send (and how many people get
|
||||
WhatsApp codes, which go by email while Accounts' WhatsApp isn't set up); Move is disabled, and
|
||||
refused by the server (`EMAIL_NOT_READY`), until Accounts' email works.
|
||||
|
||||
## [3.0.0] - 2026-11-19
|
||||
|
||||
Sign-in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md). Requires
|
||||
|
||||
+26
-15
@@ -127,13 +127,17 @@ server {
|
||||
access_log /var/log/nginx/hope-events.access.log hope_proxy;
|
||||
|
||||
# Visitors only reach this through the VPS over HTTPS, so tell the app so.
|
||||
location ~ ^/(api|uploads|health|docs)(/|$) {
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
# For the backend locations below ("location /" sets its own).
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
|
||||
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
|
||||
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
|
||||
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
|
||||
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
|
||||
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
@@ -147,7 +151,10 @@ server {
|
||||
```
|
||||
|
||||
The VPS nginx/Caddy must redirect plain HTTP to HTTPS and pass the `Host` header through to frps
|
||||
unchanged (frps picks the site by its host name). For nginx on the VPS, roughly:
|
||||
unchanged (frps picks the site by its host name). Send every path through as it is: no
|
||||
`location ~* \.(png|css|js…)$` caching rules for this site on the VPS, which would send
|
||||
`/api/uploads/…/logo.png` to the site instead of the backend. (Since 3.6.1 the site passes such
|
||||
requests on to the backend itself, but they're slower that way.) For nginx on the VPS, roughly:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
@@ -188,13 +195,17 @@ server {
|
||||
client_max_body_size 25m;
|
||||
access_log /var/log/nginx/hope-events.access.log hope_proxy;
|
||||
|
||||
location ~ ^/(api|uploads|health|docs)(/|$) {
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
# For the backend locations below ("location /" sets its own).
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
|
||||
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
|
||||
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
|
||||
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
|
||||
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
|
||||
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -765,8 +765,11 @@ registered for; always sent) or **News & announcements** (only to people who opt
|
||||
on that channel and haven't unsubscribed). News emails carry an unsubscribe link and
|
||||
one-click `List-Unsubscribe` headers; news WhatsApps end with "Reply STOP" and a link.
|
||||
Event updates say why they were sent and link to the preferences. A STOP reply on
|
||||
WhatsApp turns off WhatsApp news (through WAWP's `message` webhook, checked against a
|
||||
secret in the webhook URL).
|
||||
WhatsApp (through WAWP's `message` webhook, checked against a secret in the webhook URL)
|
||||
**stops every WhatsApp message to that number** from 3.8.0, event updates, tickets and
|
||||
codes included (they go by email), and from the church's other sites too: it's passed on
|
||||
to the church's Accounts, where the person turns WhatsApp back on (without Accounts, by
|
||||
replying START).
|
||||
|
||||
**Privacy notice** (`/legal/privacy`) — edited in **Admin → Privacy (POPIA)**
|
||||
(`/dashboard/admin/privacy`): sections start from the built-in text; drafts, preview,
|
||||
|
||||
@@ -22,12 +22,17 @@ Events password until an admin moves sign-in (step 4). The plan behind it is
|
||||
|
||||
Site settings → **Sign-in**:
|
||||
|
||||
1. **Check the move.** Nothing changes. It lists how many people move, who already has a church
|
||||
1. **Set up the church account's email** (Email and WhatsApp for the church's sign-in, on the same
|
||||
page, from 3.1.0). Accounts sends sign-in codes and password links itself, so without email there
|
||||
nobody could sign in after the move; Move stays disabled until it works. The page copies this
|
||||
site's email settings (leave the password blank to use this site's), **Send a test email**, check
|
||||
it arrived, then **Save in Accounts**. WhatsApp the same way, if you use it.
|
||||
2. **Check the move.** Nothing changes. It lists how many people move, who already has a church
|
||||
account (they're linked to it and keep that account's password), anyone who can't move and why,
|
||||
and the guests and deleted people who stay in Cross Events only.
|
||||
2. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
|
||||
3. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
|
||||
sign-in). By default every admin is ticked.
|
||||
3. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
|
||||
4. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
|
||||
closes). It takes about a minute. People already signed in stay signed in.
|
||||
|
||||
What people notice afterwards:
|
||||
|
||||
@@ -12,6 +12,85 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.8.0
|
||||
|
||||
- **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number
|
||||
gets no more WhatsApp messages from Cross Events, event updates and tickets included (they come
|
||||
by email instead), and none from your church's other sites either. Before, STOP only stopped news
|
||||
and announcements. They can turn WhatsApp back on from their account page in your church's
|
||||
sign-in (or, if your church doesn't use it, by replying START).
|
||||
- **Demo churches** for Cross Code's demo sites: eight demo churches, each with its own people,
|
||||
staff and campuses, the same as on the demo Church Website and App. Never used on a real
|
||||
church's site.
|
||||
|
||||
## 3.7.2
|
||||
|
||||
- **Fixed: events from your Church Website could show twice** after the website's content was
|
||||
replaced. Cross Events now checks the full list every 15 minutes and removes events that are gone.
|
||||
|
||||
## 3.7.1
|
||||
|
||||
- **Connecting to your new Church Website works straight away**, so its events page can show your
|
||||
Cross Events events as soon as it's installed, instead of after up to 15 minutes.
|
||||
|
||||
## 3.7.0 — requires accounts 1.7.0
|
||||
|
||||
- **Your public pages look like the rest of your church's sites.** With sign-in through your
|
||||
church's Accounts, the event pages use the fonts and corner style picked under Accounts → Admin →
|
||||
Brand style (as your sign-in pages, and later your church website, do), and a new footer shows your service times,
|
||||
address, contact details, social links and links to your other sites. The dashboard looks the same
|
||||
as before.
|
||||
|
||||
## 3.6.1
|
||||
|
||||
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
|
||||
the site can't show it yet", depending on how the server is set up. Uploaded pictures, certificate
|
||||
downloads and the like now show on those servers too.
|
||||
|
||||
## 3.6.0
|
||||
|
||||
- **People's details are checked every night.** Cross Events compares everyone's name, email,
|
||||
phone and news choices with their church account and fixes any that are out of date, and handles
|
||||
accounts that were deleted, in case a change never reached this site. You can see it, run it or
|
||||
switch it off under Settings → Background jobs. It needs Accounts 1.5.0.
|
||||
|
||||
## 3.5.0
|
||||
|
||||
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
|
||||
sign-in (Accounts). Demo data keeps it now, and a site that lost it connects again by itself
|
||||
within about 15 minutes of updating.
|
||||
- When signing in fails, Cross Code is told why, so it can help sooner.
|
||||
|
||||
## 3.4.0
|
||||
|
||||
- **Switch background jobs on and off yourself.** Settings → Background jobs has a switch for each
|
||||
job (reminders, backups, the daily summary and so on) and lets you change when it runs, with ready
|
||||
choices such as "every 15 minutes" or "daily at 07:00". It works straight away, no restart needed,
|
||||
and one click puts a job back to how the server normally runs it.
|
||||
- **Run now** works for a job that's switched off too, for when you want it once.
|
||||
|
||||
## 3.3.0
|
||||
|
||||
- **Fix:** a new logo or favicon sometimes didn't show after saving. It's saved and shown properly
|
||||
now, and logos that went missing this way come back.
|
||||
- **Fix:** signing out of this site now also signs you out of your church account.
|
||||
- Loading new demo data replaces the old demo people in the church's Accounts too.
|
||||
|
||||
## 3.2.0
|
||||
|
||||
- Cross Code now sees when an event is on at your church before an urgent update, so it isn't taken
|
||||
offline in the middle of your check-in without a good reason.
|
||||
|
||||
## 3.1.0 — requires accounts 1.2.0
|
||||
|
||||
- **Fix:** moving sign-in to your church's Accounts now needs Accounts' email to work first, so
|
||||
people can always get their sign-in codes and password links. Settings → Sign-in shows whether it
|
||||
does, and sets it up for you: it copies this site's email settings (your password stays where it
|
||||
is), sends a test, and only saves them in Accounts once the test arrived. The same for WhatsApp.
|
||||
- If your church already moved without it, the same page sets it up now.
|
||||
- The church's sign-in page now has your logo and colours: they're taken from this site when you
|
||||
move, and **Use this site's logo and colours** (Settings → Sign-in) updates them any time.
|
||||
|
||||
## 3.0.0 — requires accounts 1.1.0
|
||||
|
||||
- **One sign-in for all your church's sites and apps.** People can now sign in to Cross Events with
|
||||
|
||||
@@ -11,7 +11,27 @@ showing it to:
|
||||
| `npm run demo:ministry` | One campus with weekly ministry | The Alpha Course running now (sessions, attendance, late joining, certificates), a finished Marriage Course with certificates, a 3-day conference sold by day, **Kids Church** with families, children, rooms and check-ins, **volunteer rosters**, a **Men's Breakfast series** with followers and a **season pass**, plus a family day, women's conference and carols. |
|
||||
| `npm run demo:multicampus` | A church with several campuses | **Campuses** Central, North and South (switched on), events per campus and church-wide, home campuses, staff limited to a campus (Anri Botha → North, Daniel Pillay → South), the breakfast series moving between campuses, kids church and rosters at two campuses, and all the events-demo events spread over the campuses. |
|
||||
|
||||
`npm run demo:list` prints the same list. Kids church always has a session **today** with
|
||||
**3.8.0: the eight demo scenarios** (docs/APP-1.0-PLAN.md §12). Each is named after its
|
||||
Website demo profile and is one of the churches every product of a demo client shows:
|
||||
|
||||
| Profile | Church | Built as |
|
||||
|---|---|---|
|
||||
| `heritage-parish` | St Columba's Church | small |
|
||||
| `heritage-city` | Grace Cathedral | events |
|
||||
| `bold-youth` | Ignite Church | events |
|
||||
| `bold-plant` | Harbour City Church | small |
|
||||
| `community-family` | Acacia Hill Church (cross-demo2) | ministry |
|
||||
| `community-town` | Karoo Gemeenskapskerk | small |
|
||||
| `clean-modern` | Northpoint Church | ministry |
|
||||
| `clean-campus` | Riverside Church (three campuses) | multicampus |
|
||||
|
||||
They use the church's own people from `@crosscode/demo` (its leads are the staff and the event
|
||||
contacts; the same people, with the same accounts, as in Accounts, the Website and the App) and
|
||||
its own campuses. Load Accounts' part first (`crosscode demo <church> accounts --profile …`), then
|
||||
`npm run set-demo -- --profile=<scenario> --yes` (or `crosscode demo <church> --profile <scenario>`).
|
||||
A small church's events sell only to the people it has.
|
||||
|
||||
`npm run demo:list` prints every profile. Kids church always has a session **today** with
|
||||
children checked in right now, so the kids desk and room screens have something live to
|
||||
show on any day.
|
||||
|
||||
@@ -63,9 +83,13 @@ previous demo and creates it again.
|
||||
| The admin account, including its login history, trusted devices and 2FA | Every other user |
|
||||
| Migration history | Registrations, payments, tickets, scans, coupons, waitlists, consents, cabins, feedback, analytics, audit log |
|
||||
| Uploaded files on disk (`public/uploads`) | Queued scheduled emails/WhatsApps (`data/scheduled-emails.json`) |
|
||||
| Links to the church's other products (Accounts, the Website) | Copies of the linked products' events (fetched again straight away) |
|
||||
| The event feed's history: the old events are listed as removed | |
|
||||
|
||||
The wipe and the new data are written in one database transaction. If that fails,
|
||||
nothing changes. The past events' cashups run straight afterwards, through the same
|
||||
nothing changes. Since 3.7.2 the script then publishes the new events in the event feed and
|
||||
tells the linked products (the Church Website), so their next page load shows the new events
|
||||
and not the old ones, and fetches the linked products' events back in. The past events' cashups run straight afterwards, through the same
|
||||
code as the cashup screen. If one of those fails, re-run the script.
|
||||
|
||||
---
|
||||
|
||||
@@ -145,7 +145,7 @@ npm run prisma:generate
|
||||
|
||||
### Demo data
|
||||
|
||||
`npm run set-demo -- --profile=<small|events|ministry|multicampus>` wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
|
||||
`npm run set-demo -- --profile=<small|events|ministry|multicampus|a demo scenario>` (3.8.0: the eight scenarios, e.g. `community-family`) wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.0.0",
|
||||
"version": "3.8.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
@@ -25,6 +25,7 @@
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Cross Events 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): STOP to the church's WhatsApp number
|
||||
-- means no WhatsApp from any of its products. Kept per account (from Accounts) and per number.
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false;
|
||||
-- CreateTable
|
||||
CREATE TABLE "WhatsAppStop" (
|
||||
"phone" TEXT NOT NULL,
|
||||
"keyword" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"receivedAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "WhatsAppStop_pkey" PRIMARY KEY ("phone")
|
||||
);
|
||||
@@ -95,6 +95,10 @@ model User {
|
||||
newsWhatsApp Boolean @default(false)
|
||||
// When the person last answered the news opt-in question. Null = ask at next login.
|
||||
newsAskedAt DateTime?
|
||||
// 3.8.0: replied STOP to the church's WhatsApp number (here or to another of the church's
|
||||
// products; Accounts keeps it and sends it in user.updated): no WhatsApp of any kind, until
|
||||
// they turn it back on in Accounts. See also WhatsAppStop (by number).
|
||||
whatsappOptedOut Boolean @default(false)
|
||||
// The privacy notice version they last accepted (0 = the built-in notice). Null = never
|
||||
// recorded. Asked again when a version that needs re-acceptance is newer.
|
||||
noticeVersionAccepted Int?
|
||||
@@ -1893,6 +1897,16 @@ model CommunicationConsent {
|
||||
|
||||
// Addresses (email, or phone as 27…) that unsubscribed from news without an account,
|
||||
// e.g. ad-hoc broadcast recipients. News broadcasts skip them.
|
||||
// 3.8.0 (docs/APP-1.0-PLAN.md §8, decision 11): numbers that replied STOP to the church's WhatsApp
|
||||
// number. Nothing goes to them on WhatsApp (src/utils/whatsappStop.js), with or without an account.
|
||||
model WhatsAppStop {
|
||||
phone String @id // 27821234567
|
||||
keyword String
|
||||
source String // events (this site's webhook) | accounts
|
||||
receivedAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model MessagingOptOut {
|
||||
id String @id @default(uuid())
|
||||
channel String // email | whatsapp
|
||||
|
||||
@@ -16,6 +16,13 @@
|
||||
* campus-limited staff, a series across campuses, kids check-in and rosters at two
|
||||
* campuses.
|
||||
*
|
||||
* 3.8.0: and one per demo scenario (docs/APP-1.0-PLAN.md §12; contracts agent.DEMO_SCENARIOS),
|
||||
* named after it (heritage-parish … clean-campus). A scenario's demo is built from one of the four
|
||||
* kinds above, but around the scenario's own church: its people from @crosscode/demo (the same
|
||||
* people, with the same church accounts, as in Accounts, the Website and the App; leads become the
|
||||
* staff), and its own campuses. Load Accounts first (crosscode demo <church> accounts …), which
|
||||
* makes those people's accounts; the demo then links to them rather than removing them.
|
||||
*
|
||||
* Everything is removed first EXCEPT the site settings (AppSetting) and one admin
|
||||
* account (--admin-email= or DEMO_ADMIN_EMAIL; else joshua@crosscode.co.za, else the oldest admin).
|
||||
* Dates are relative to
|
||||
@@ -58,6 +65,8 @@ const { hashPassword } = require('../src/config/auth');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const { createPrismaClient } = require('../src/config/db');
|
||||
const { applyBundles } = require('../src/utils/bundles');
|
||||
const { agent } = require('@crosscode/contracts');
|
||||
const demo = require('@crosscode/demo');
|
||||
|
||||
const prisma = createPrismaClient();
|
||||
|
||||
@@ -76,6 +85,12 @@ const LIST_ONLY = process.argv.includes('--list');
|
||||
const KEEP_TABLES = new Set([
|
||||
'_prisma_migrations', 'AppSetting', 'User',
|
||||
'SecurityEvent', 'PasswordReset', 'TwoFactorChallenge', 'TrustedDevice',
|
||||
// 3.5.0: the links to the church's other products (Accounts above all: in Accounts mode, without
|
||||
// its link nobody can sign in). Their feeds are data and go.
|
||||
'ProductLink', 'LinkNonce',
|
||||
// 3.7.2: what the feed last published. Its live entries are marked removed instead (clearData),
|
||||
// so linked products are told the old events are gone, not left showing them beside the new.
|
||||
'FeedEntry',
|
||||
]);
|
||||
|
||||
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
|
||||
@@ -230,7 +245,34 @@ function addUser({ first, last, gender, role = 'user', email }) {
|
||||
return user;
|
||||
}
|
||||
|
||||
/** The name of the nth demo staff member (the contact on events), for every profile. */
|
||||
const staffName = (n) => (staffTeam[n] || staffTeam[0]).name;
|
||||
|
||||
/** The Events roles the scenario's leads get, in this order: the first four are the demo staff. */
|
||||
const STAFF_PARTS = ['pastor', 'office', 'youth', 'worship', 'kids', 'prayer-coordinator'];
|
||||
/** People in a scenario's Events demo besides its leads: not every member uses Events. */
|
||||
const SCENARIO_MEMBERS = 260;
|
||||
|
||||
/** 3.8.0: a scenario's people (@crosscode/demo), as Accounts has them. */
|
||||
function buildScenarioPeople(scenario) {
|
||||
const all = demo.demoPeople(scenario);
|
||||
const leads = all.filter(x => x.part !== 'member');
|
||||
const staff = STAFF_PARTS.map(part => leads.find(x => x.part === part)).filter(Boolean).slice(0, 4);
|
||||
const asUser = (person, role) => {
|
||||
const user = addUser({ first: person.givenName, last: person.familyName, gender: person.gender, role, email: person.email });
|
||||
userMeta.get(user.id).campus = person.campus;
|
||||
return user;
|
||||
};
|
||||
staff.forEach((person, n) => staffTeam.push(asUser(person, n === 0 ? 'supervisor' : 'staff')));
|
||||
const others = leads.filter(x => !staff.includes(x)).concat(all.filter(x => x.part === 'member').slice(0, SCENARIO_MEMBERS));
|
||||
const users = others.map(person => asUser(person, 'user'));
|
||||
const women = users.filter(u => userMeta.get(u.id).gender === 'female');
|
||||
const men = users.filter(u => userMeta.get(u.id).gender === 'male');
|
||||
return { women, men, everyone: women.concat(men) };
|
||||
}
|
||||
|
||||
function buildPeople() {
|
||||
if (profile.scenario) return buildScenarioPeople(profile.scenario);
|
||||
staffTeam.push(
|
||||
addUser({ first: 'Lerato', last: 'Khumalo', gender: 'female', role: 'supervisor', email: 'lerato.khumalo@example.com' }),
|
||||
addUser({ first: 'Sipho', last: 'Dlamini', gender: 'male', role: 'staff', email: 'sipho.dlamini@example.com' }),
|
||||
@@ -253,7 +295,7 @@ function addEvent(data) {
|
||||
goLiveAt: addTime(NOW, -35 * DAY),
|
||||
createdAt: addTime(NOW, -38 * DAY),
|
||||
isActive: true,
|
||||
contactName: 'Lerato Khumalo',
|
||||
contactName: staffName(0),
|
||||
contactEmail: 'events@example.com',
|
||||
contactPhone: '021 555 0142',
|
||||
...data,
|
||||
@@ -533,7 +575,7 @@ function buildMensBreakfast(people) {
|
||||
picture: IMG('photo-1414235077428-338989a2e8c0'),
|
||||
location: 'Church hall',
|
||||
waitlistEnabled: true,
|
||||
contactName: 'Sipho Dlamini',
|
||||
contactName: staffName(1),
|
||||
});
|
||||
const ticket = addOption(event, { name: 'Breakfast ticket', price: 150, stockLimit: 60 });
|
||||
addSection(event, 'Hall entrance', [ticket]);
|
||||
@@ -542,16 +584,17 @@ function buildMensBreakfast(people) {
|
||||
|
||||
const men = shuffle(people.men);
|
||||
let sold = 0;
|
||||
while (sold < 60) {
|
||||
// 3.8.0: a small scenario church has fewer men than seats: sold to all of them, the rest left open.
|
||||
while (sold < 60 && men.length > 7) {
|
||||
const user = men.shift();
|
||||
const quantity = Math.min(chance(0.2) ? 2 : 1, 60 - sold);
|
||||
sold += quantity;
|
||||
addRegistration(event, user, [line(ticket, quantity)], { createdAt: pastDate(28), ...payPlan({ card: 0.65, cash: 0.15, eft: 0.08, none: 0.12 }) });
|
||||
}
|
||||
for (let i = 0; i < 2; i++) {
|
||||
for (let i = 0; i < 2 && men.length; i++) {
|
||||
addRegistration(event, men.shift(), [line(ticket, 1)], { createdAt: pastDate(25, 5), pay: 'cancelled' });
|
||||
}
|
||||
for (let position = 1; position <= 5; position++) {
|
||||
for (let position = 1; position <= 5 && sold >= 60 && men.length; position++) {
|
||||
add('waitlistEntry', {
|
||||
id: uuidv4(), eventId: event.id, eventOptionId: ticket.id, userId: men.shift().id,
|
||||
quantity: position === 3 ? 2 : 1, position, status: 'waiting', createdAt: pastDate(4),
|
||||
@@ -574,7 +617,7 @@ function buildWomensConference(people) {
|
||||
price: 450,
|
||||
picture: IMG('photo-1511632765486-a01980e01a18'),
|
||||
location: 'Main auditorium',
|
||||
contactName: 'Anri Botha',
|
||||
contactName: staffName(2),
|
||||
});
|
||||
const full = addOption(event, { name: 'Full conference (Fri + Sat)', price: 450 });
|
||||
const saturday = addOption(event, { name: 'Saturday only', price: 280 });
|
||||
@@ -653,7 +696,7 @@ function buildYouthCamp(people) {
|
||||
collectGender: true,
|
||||
allowSponsorships: true,
|
||||
sponsorshipGoalSpots: 10,
|
||||
contactName: 'Daniel Pillay',
|
||||
contactName: staffName(3),
|
||||
});
|
||||
const camper = addOption(event, { name: 'Camper (Grade 7–12)', price: 1650, stockLimit: 80 });
|
||||
const hoodie = addOption(event, { name: 'Camp hoodie', price: 380, isMainTicket: false });
|
||||
@@ -792,7 +835,7 @@ function buildMarriageWeekend(people) {
|
||||
price: 3400,
|
||||
picture: IMG('photo-1606800052052-a08af7148866'),
|
||||
location: 'Kloofzicht Lodge, Muldersdrift',
|
||||
contactName: 'Lerato Khumalo',
|
||||
contactName: staffName(0),
|
||||
});
|
||||
const couple = addOption(event, { name: 'Couple package (2 nights)', price: 3400 });
|
||||
const [garden, mountain] = addVariants(couple, [
|
||||
@@ -881,22 +924,26 @@ function buildPastEvent(people, spec) {
|
||||
for (const [label, type, amount, option] of spec.costs(opts)) addCost(event, label, type, amount, option || null);
|
||||
|
||||
const buyers = shuffle(people[spec.pool || 'everyone']);
|
||||
const nextBuyer = () => {
|
||||
if (buyers.length === 0) throw new Error(`Not enough demo people for ${spec.title}`);
|
||||
return buyers.shift();
|
||||
};
|
||||
// 3.8.0: a small scenario church runs out of people before the event fills: the sales stop there.
|
||||
const nextBuyer = () => buyers.shift() || null;
|
||||
const salesFrom = addTime(start, -35 * DAY);
|
||||
const payBy = addTime(start, -HOUR);
|
||||
for (let i = 0; i < spec.online; i++) {
|
||||
const plan = typeof spec.onlinePay === 'function' ? spec.onlinePay() : payPlan(spec.onlinePay);
|
||||
addRegistration(event, nextBuyer(), spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -DAY)), payBy, ...plan });
|
||||
const buyer = nextBuyer();
|
||||
if (!buyer) break;
|
||||
addRegistration(event, buyer, spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -DAY)), payBy, ...plan });
|
||||
}
|
||||
for (let i = 0; i < (spec.refunds || 0); i++) {
|
||||
addRegistration(event, nextBuyer(), spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -10 * DAY)), pay: 'refunded', method: 'card' });
|
||||
const buyer = nextBuyer();
|
||||
if (!buyer) break;
|
||||
addRegistration(event, buyer, spec.lines(opts, false), { createdAt: daytimeBetween(salesFrom, addTime(start, -10 * DAY)), pay: 'refunded', method: 'card' });
|
||||
}
|
||||
for (let i = 0; i < (spec.door || 0); i++) {
|
||||
const method = weighted(spec.doorPay || { cash: 70, card: 30 });
|
||||
addRegistration(event, nextBuyer(), spec.lines(opts, true), { createdAt: within(addTime(start, -30 * MINUTE), addTime(start, HOUR)), method, atDoor: true });
|
||||
const buyer = nextBuyer();
|
||||
if (!buyer) break;
|
||||
addRegistration(event, buyer, spec.lines(opts, true), { createdAt: within(addTime(start, -30 * MINUTE), addTime(start, HOUR)), method, atDoor: true });
|
||||
}
|
||||
|
||||
const { card = 0, cash = 0, amounts = [] } = spec.donations || {};
|
||||
@@ -1301,6 +1348,23 @@ const PROFILES = {
|
||||
},
|
||||
};
|
||||
|
||||
/** 3.8.0: the kind of demo each scenario is built from (APP-1.0-PLAN §12, the "Events" column). */
|
||||
const SCENARIO_KINDS = {
|
||||
'heritage-parish': 'small', 'heritage-city': 'events', 'bold-youth': 'events', 'bold-plant': 'small',
|
||||
'community-family': 'ministry', 'community-town': 'small', 'clean-modern': 'ministry', 'clean-campus': 'multicampus',
|
||||
};
|
||||
for (const scenario of agent.DEMO_SCENARIOS) {
|
||||
const kind = PROFILES[SCENARIO_KINDS[scenario.key]];
|
||||
const church = demo.demoChurch(scenario.key);
|
||||
PROFILES[scenario.key] = {
|
||||
...kind,
|
||||
scenario: scenario.key,
|
||||
title: `${church.profile.name} — demo scenario (${scenario.label.split(':')[0]})`,
|
||||
about: [scenario.description, `Built as the "${SCENARIO_KINDS[scenario.key]}" demo, with ${church.profile.name}'s own people${kind.campuses ? ' and campuses' : ''}. Load Accounts' part first.`],
|
||||
campuses: church.profile.campuses.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
let profile = PROFILES[PROFILE_NAME];
|
||||
|
||||
const hex = (bytes = 16) => crypto.randomBytes(bytes).toString('hex');
|
||||
@@ -1310,9 +1374,23 @@ let campuses = [];
|
||||
|
||||
function buildCampuses() {
|
||||
const campus = (name, slug, address, colour, defaultLocation, order) => add('campus', {
|
||||
id: uuidv4(), name, slug, address, contactName: 'Lerato Khumalo', contactEmail: `${slug}@example.com`,
|
||||
id: uuidv4(), name, slug, address, contactName: staffName(0), contactEmail: `campus.${slug}@example.com`,
|
||||
colour, defaultLocation, order, createdAt: addTime(NOW, -300 * DAY), updatedAt: NOW,
|
||||
});
|
||||
if (profile.scenario) {
|
||||
// 3.8.0: the scenario church's own campuses, and people at the campus Accounts gives them.
|
||||
const colours = ['#2563eb', '#16a34a', '#ea580c'];
|
||||
campuses = demo.demoChurch(profile.scenario).profile.campuses.map((c, n) => campus(
|
||||
c.name, c.slug, c.address ? [c.address.line1, c.address.suburb, c.address.city].filter(Boolean).join(', ') : null,
|
||||
colours[n % colours.length], n === 0 ? 'Main auditorium' : `${c.name} campus hall`, n,
|
||||
));
|
||||
for (const u of rows.user) {
|
||||
const slug = userMeta.get(u.id)?.campus;
|
||||
const home = campuses.find(c => c.slug === slug);
|
||||
if (u.role === 'user' && home) u.homeCampusId = home.id;
|
||||
}
|
||||
return;
|
||||
}
|
||||
campuses = [
|
||||
campus('Central', 'central', '12 Church Street, Hatfield, Pretoria', '#2563eb', 'Main auditorium', 0),
|
||||
campus('North', 'north', '45 Zambezi Drive, Montana', '#16a34a', 'North campus hall', 1),
|
||||
@@ -1339,9 +1417,10 @@ function assignCampuses() {
|
||||
|
||||
/** Staff limited to one campus (a many-to-many, so it's set after the rows are in). */
|
||||
async function scopeStaff(tx) {
|
||||
const byName = (first) => staffTeam.find(s => s.name.startsWith(first));
|
||||
for (const [first, campusIdx] of [['Anri', 1], ['Daniel', 2]]) {
|
||||
await tx.user.update({ where: { id: byName(first).id }, data: { scopedCampuses: { connect: [{ id: campuses[campusIdx].id }] } } });
|
||||
// The third and fourth demo staff (Anri Botha and Daniel Pillay in the multicampus demo).
|
||||
for (const [staffIdx, campusIdx] of [[2, 1], [3, 2]]) {
|
||||
if (!staffTeam[staffIdx] || !campuses[campusIdx]) continue;
|
||||
await tx.user.update({ where: { id: staffTeam[staffIdx].id }, data: { scopedCampuses: { connect: [{ id: campuses[campusIdx].id }] } } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1357,7 +1436,7 @@ function buildBreakfast(people, { start, title, sold }) {
|
||||
price: 150,
|
||||
picture: IMG('photo-1414235077428-338989a2e8c0'),
|
||||
location: 'Church hall',
|
||||
contactName: 'Sipho Dlamini',
|
||||
contactName: staffName(1),
|
||||
});
|
||||
const ticket = addOption(event, { name: 'Breakfast ticket', price: 150, stockLimit: 60 });
|
||||
addCost(event, 'Breakfast catering', 'per_item', 85, ticket);
|
||||
@@ -1741,8 +1820,8 @@ function buildExtras(people, built) {
|
||||
function listProfiles() {
|
||||
console.log('\nDemo profiles — npm run demo:<name> (from the repo root):\n');
|
||||
for (const [name, p] of Object.entries(PROFILES)) {
|
||||
console.log(` ${name.padEnd(12)} ${p.title}`);
|
||||
for (const line of p.about) console.log(` ${''.padEnd(12)} ${line}`);
|
||||
console.log(` ${name.padEnd(17)} ${p.title}`);
|
||||
for (const line of p.about) console.log(` ${''.padEnd(17)} ${line}`);
|
||||
console.log('');
|
||||
}
|
||||
}
|
||||
@@ -1820,6 +1899,10 @@ async function clearData(tx) {
|
||||
await tx.$executeRawUnsafe(`UPDATE "User" SET ${[...new Set(userRefs.map(r => `"${r.column}" = NULL`))].join(', ')}`);
|
||||
for (const table of deleteInstead) await tx.$executeRawUnsafe(`DELETE FROM "${table}"`);
|
||||
}
|
||||
// 3.7.2: every event the feed published goes into its `deleted` list, and the copies of linked
|
||||
// products' events (truncated above) are fetched again in full.
|
||||
await tx.feedEntry.updateMany({ where: { removedAt: null }, data: { removedAt: new Date() } });
|
||||
await tx.productLink.updateMany({ data: { lastGoodAt: null } });
|
||||
// Their password resets, 2FA codes and trusted devices go with them (onDelete: Cascade).
|
||||
const { count } = await tx.user.deleteMany({ where: { id: { not: admin.id } } });
|
||||
await tx.securityEvent.deleteMany({ where: { OR: [{ userId: null }, { userId: { not: admin.id } }] } });
|
||||
@@ -1880,6 +1963,7 @@ async function main() {
|
||||
}
|
||||
|
||||
passwordHash = await hashPassword(DEMO_PASSWORD);
|
||||
const scenarioSubs = new Set(profile.scenario ? demo.demoPeople(profile.scenario).map(x => x.id) : []);
|
||||
const people = buildPeople();
|
||||
if (profile.campuses) buildCampuses();
|
||||
const events = profile.upcoming.map(key => UPCOMING[key](people));
|
||||
@@ -1888,6 +1972,11 @@ async function main() {
|
||||
if (profile.campuses) assignCampuses();
|
||||
buildAnalytics();
|
||||
|
||||
// 3.3.0: the church accounts of the people about to be cleared, so the old demo people leave
|
||||
// Accounts too (only demo addresses; Accounts checks).
|
||||
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId)
|
||||
// 3.8.0: a scenario's people belong to Accounts' part of the scenario (loaded first): linked again, never removed.
|
||||
.filter(sub => !scenarioSubs.has(sub));
|
||||
const cleared = await prisma.$transaction(async (tx) => {
|
||||
const result = await clearData(tx);
|
||||
for (const model of INSERT_ORDER) {
|
||||
@@ -1904,7 +1993,8 @@ async function main() {
|
||||
}, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 });
|
||||
clearScheduledEmails();
|
||||
const pastFinancials = await closePastEvents();
|
||||
const accounts = await demoAccounts();
|
||||
const accounts = await demoAccounts(oldSubs);
|
||||
const feed = await demoFeed();
|
||||
|
||||
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
|
||||
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
|
||||
@@ -1954,18 +2044,55 @@ async function main() {
|
||||
for (const s of staffTeam) console.log(` ${s.role.padEnd(10)} ${s.email}`);
|
||||
console.log(`Every other demo person also uses ${DEMO_PASSWORD}.`);
|
||||
if (accounts) {
|
||||
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
|
||||
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
|
||||
}
|
||||
if (feed && feed.links) console.log(`Connected products: ${feed.told} of ${feed.links} told the events changed${feed.failed ? `; ${feed.failed} couldn't be fetched from (the next poll catches up)` : ''}.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The backend's own code: the compiled code (dist/) on a server, the TypeScript through tsx in
|
||||
* development. With dist/, its database client is a second one, disconnected at the end.
|
||||
*/
|
||||
function backendModule(rel) {
|
||||
const dist = path.join(__dirname, '..', 'dist', `${rel}.js`);
|
||||
if (fs.existsSync(dist)) {
|
||||
accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db'));
|
||||
return require(dist);
|
||||
}
|
||||
require('tsx/cjs');
|
||||
return require(`../src/${rel}.ts`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 3.7.2: the new events published in the feed straight away, linked products (the Website) told,
|
||||
* so their next page load shows the new events without the old (marked removed in clearData), and
|
||||
* their events fetched back in. Never fails the demo: the jobs catch up within 15 minutes.
|
||||
*/
|
||||
async function demoFeed() {
|
||||
try {
|
||||
const { refreshAndNotify } = backendModule('feed/notify');
|
||||
const { syncAll } = backendModule('feed/sync');
|
||||
const { told } = await refreshAndNotify(new Date());
|
||||
const synced = await syncAll(new Date());
|
||||
const links = await prisma.productLink.count();
|
||||
return { links, told, failed: synced.failed };
|
||||
} catch (e) {
|
||||
console.warn(`[warn] The feed couldn't be refreshed now (${e.message}); the backend's feed jobs catch up within 15 minutes.`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 3.0.0: with sign-in through the church's Accounts, the demo people are moved there too (with the
|
||||
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). A demo person whose
|
||||
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). 3.3.0: first, the last
|
||||
* demo's people (`oldSubs`) are removed from Accounts (removeDemoPeople), so Accounts has the
|
||||
* same people as the site. A demo person whose
|
||||
* email already has an account from an earlier demo is linked to it. The compiled code (dist/) on a
|
||||
* server; the TypeScript through tsx in development.
|
||||
*/
|
||||
let accountsDb = null;
|
||||
async function demoAccounts() {
|
||||
async function demoAccounts(oldSubs = []) {
|
||||
const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js');
|
||||
let move;
|
||||
if (fs.existsSync(dist)) {
|
||||
@@ -1978,7 +2105,12 @@ async function demoAccounts() {
|
||||
const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } });
|
||||
if (mode?.value !== 'accounts') return null;
|
||||
try {
|
||||
return await move.moveNewPeople(admin.accountId || null);
|
||||
// Accounts before 1.3.0 doesn't know the request: the new demo still moves, the old stays.
|
||||
const gone = await move.removeDemoPeople(oldSubs, admin.accountId || null).catch((e) => {
|
||||
console.warn(`[warn] The last demo's people couldn't be removed from Accounts (${e.message}); they stay there until Accounts is updated to 1.3.0 and the demo is loaded again.`);
|
||||
return { removed: 0 };
|
||||
});
|
||||
return { ...(await move.moveNewPeople(admin.accountId || null)), removed: gone.removed };
|
||||
} catch (e) {
|
||||
console.warn(`[warn] The demo people couldn't be moved to Accounts (${e.message}). Run the demo again once Accounts can be reached.`);
|
||||
process.exitCode = 1;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user