Compare commits

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:26:50 +02:00
joshua cacbb16895 Merge branch 'fix/accounts-link' 2026-11-20 12:56:39 +02:00
joshuaandClaude Opus 5.5 08b58ae310 Events 3.5.0, contracts 1.13.0, agent 1.3.1: demo data keeps the Accounts link; sign-in health for the Hub
- Events: loading demo data emptied ProductLink but kept auth_mode, so a site in Accounts mode had
  no link and nobody could sign in (ACCOUNTS_UNAVAILABLE on events-demo). set-demo.js keeps
  ProductLink and LinkNonce; a site in Accounts mode without a link reconnects at its next
  heartbeat; sign-in failures are kept and sent in the heartbeat (stats.signIn).
- Contracts 1.13.0: stats.signIn in the Cross Events heartbeat.
- Agent 1.3.1: 1.3.0 reported itself as 1.2.0 (AGENT_VERSION not bumped).
- What's New notes for Events 3.4.0 / 3.5.0 and Accounts 1.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:56:37 +02:00
joshua e32a3b6144 Merge branch 'feat/env-and-jobs' 2026-11-20 12:14:04 +02:00
joshuaandClaude Opus 5.5 bbcafe61b9 Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:02 +02:00
joshuaandClaude Opus 5.5 a85347bff8 Merge branch 'feat/accounts-1.3'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:20:02 +02:00
joshuaandClaude Opus 5.5 8856d6b35d Events 3.3.0, Accounts 1.3.0, contracts 1.11.0: Accounts looks like Events, backups; sign-out and upload fixes
- Accounts: account and admin pages in Cross Events' layout (top bar, sidebar,
  a page per section, dark footer); quick links to the church's sites
  (GET /me/apps); nightly pg_dump backups with Admin -> Backups (run, keep,
  download, audited; heartbeat lastBackupAt); a fuller built-in privacy notice
  with headings and bullets; a fixed favicon. /backups/ ignored (anchored, so
  src/backups is kept).
- Contracts 1.11.0: people.removeDemo (only @example.com, never an admin).
- Events: uploads served from the folder they're saved in (a backend started
  outside backend/ answered 404 for a logo it had just saved); Branding checks
  the file loads before saving; logout waits for the sign-out call so Accounts
  signs out too; set-demo removes the last demo's people from Accounts.
Tests: Accounts 62 + e2e 8, Events 782, contracts 225; npm run check passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:19:57 +02:00
joshuaandClaude Opus 5.5 8ee64bb9c9 docs: VERSIONS.md for Hub 2.7.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:17:16 +02:00
joshua 293a9b73e5 Merge branch 'feat/emergency-now' 2026-11-19 22:04:05 +02:00
joshuaandClaude Opus 5.5 621821f5c0 Events 3.2.0, contracts 1.10.0: the heartbeat says what's on now
stats.live (eventsNow: a session or a one-day event on now, +/- 30 min;
checkInsLastHour) so Hub 2.7.0 asks again before an emergency update takes
a site with an event on down. Decision 39: emergency updates can run as
soon as possible (decision 30 changed). Tests: liveNow, Events 776.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:03:32 +02:00
joshua 88b3e1fb36 Merge branch 'feat/accounts-messaging' 2026-11-19 21:50:13 +02:00
joshuaandClaude Opus 5.5 70c471666b Accounts sign-in looks like the church's site; Events sends its logo and colours
- @crosscode/ui: Shell with the church's colour wash, logo (or its initial)
  and name, footer; Card edged in the church's colour; Heading with an
  icon tile. Icons on every sign-in step.
- contracts 1.9.0: churchLookSchema (logo, accent colour) in import.begin;
  church.branding request. Accounts fills (move) or replaces (button) the
  church profile's name, logo and colours.
- Events 3.1.0: src/accounts/look.ts (logo as a full address), sent with a
  move; Settings -> Sign-in "Use this site's logo and colours".
Tests: Accounts 55, contracts 218, Events 774, test:accounts 16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:50:02 +02:00
joshuaandClaude Opus 5.5 cc18b7b514 Events 3.1.0, Accounts 1.2.0, contracts 1.9.0: the move needs Accounts' email
A church moved sign-in to Accounts without email set up there: codes and
password links couldn't be sent, sign-in failed with a 500, nobody could
get in.

- contracts 1.9.0: messaging.status/test/set (SMTP, WAWP; secrets sealed);
  people.ensure answers emailSent.
- Accounts 1.2.0: SendError instead of a 500; WhatsApp codes fall back to
  email; forgot password says email isn't set up; setup only offers
  methods that work; messaging.* (test, save only what worked); test
  WhatsApp in admin; WAWP from .env.
- Events 3.1.0: Settings -> Sign-in shows what Accounts can send and
  copies this site's SMTP/WAWP into it (secrets stay on the server), test
  then save; Move disabled and refused (EMAIL_NOT_READY) without email.
Tests: Accounts 54, contracts 218, Events 774, test:accounts 16 (also on
Postgres).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:41:31 +02:00
joshuaandClaude Opus 5.5 4b28fc485b docs: VERSIONS.md for Hub 2.6.0 and the script fix
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:12:30 +02:00
joshua 793831ca44 Merge branch 'fix/accounts-pm2-config' 2026-11-19 20:11:42 +02:00
joshuaandClaude Opus 5.5 4b033a1d1d crosscode: Accounts' own PM2 config no longer stops deploys
install/add writes apps/accounts/ecosystem.config.cjs, which no .gitignore
covered, so the next deploy refused: "?? apps/accounts/ecosystem.config.cjs
... changed or added by hand". local_changes skips the PM2 configs the
script makes (also in existing checkouts); apps/accounts/.gitignore for
future releases. bats test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:09:44 +02:00
joshua 9bcd24bbbd Merge branch 'feat/events-3.0' 2026-11-19 15:20:02 +02:00
joshuaandClaude Opus 5.5 c9f8cad13f Release events@3.0.0, accounts@1.1.0, contracts@1.8.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:20:01 +02:00
joshuaandClaude Opus 5.5 5819ea87fb e2e: sign-in spec enters the emailed code; linked-products waits for the click and the 60 s cache
The Events e2e suite on Postgres: 111/111 (volunteers 'asks for cover' is
flaky: it passed alone and in the run before).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:19:26 +02:00
joshuaandClaude Opus 5.5 cbd7965fcc crosscode: Events 3.0 builds auth-client; tests on real Postgres
- scripts/products/events.sh: packages/auth-client is installed and built
  (after contracts) when Events uses it, as 3.0.0 does; without it a 3.0
  deploy would fail at the first sign-in through Accounts. bats test.
- test:accounts runs on real Postgres for both apps with
  EVENTS_TEST_DATABASE_URL and ACCOUNTS_TEST_DATABASE_URL (14/14); the
  Accounts test harness takes a real Prisma client.
- e2e/excel.spec.ts resolves excelts from the backend (hoisted in the
  monorepo), so the e2e suite loads again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:45:17 +02:00
joshuaandClaude Opus 5.5 be5b56673a docs: handover for Events 3.0 (built on branches in three repos)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:31:18 +02:00
joshuaandClaude Opus 5.5 63d36c3ecf Events 3.0: auto-connect, demo people in Accounts, e2e; import.finish checks the subs
- contracts 1.8.0 / Accounts 1.1.0: import.finish lists the subs the product
  relies on; Accounts checks each is held, not deleted and known to it (the
  count+hash failed a second move after Undo once someone had joined
  through Accounts).
- Events: connects to the church's Accounts once the Hub lists it;
  moveNewPeople (demo data, people added after the move); set-demo moves
  demo people; e2e/sign-in-accounts.spec.ts with Accounts in memory and an
  e2e-only /api rewrite. test:accounts 14/14; Jest auto-connect tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:54 +02:00
joshuaandClaude Opus 5.5 c627c61de1 Cross Events 3.0.0: sign-in through the church's Accounts
Settings -> Sign-in: check, move (everyone into Accounts with their password
hashes and authenticator apps, count/hash check, then switch) and undo for
14 days. Sign-in through auth-client with a one-time handoff to Events' own
token; staff roles stepped up to mfa; sign-out and back-channel logout;
user.updated/export/deleted; admin 2FA reset, unlock and profile changes via
Accounts; /login, /register, /forgot-password forward once moved; Events'
own sign-in endpoints answer SIGN_IN_MOVED. User.accountId, AccountsSignIn.

npm run test:accounts runs Events' code against the real Accounts app (11
tests); 5 new Jest tests. MIGRATING-TO-3.md, plan "Changes while building".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:10:30 +02:00
joshuaandClaude Opus 5.5 56cbef1d9b Accounts 1.1.0: the migration sorts after init
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:41:35 +02:00
joshuaandClaude Opus 5.5 733992e917 Accounts 1.1.0: moving Events' users in, people.* requests, new recovery codes
POST /api/accounts/v1/requests (crosscode.identity-request/1): import.* keeps
each person's Events id as sub, password hash and authenticator secret
(sealed in transit), consent, notices and lockout; linked when the email
already has an account. people.* for product admins, limited to people the
product knows. New recovery codes after the first 2FA sign-in for people
moved in with 2FA. screen=signup. auth-client: request(), seal(), signUp.
8 new tests (47 in all).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:40:15 +02:00
joshuaandClaude Opus 5.5 08fef930c1 contracts 1.8.0: crosscode.identity-request/1 (import and people.* calls to Accounts)
Product -> Accounts requests at /api/accounts/v1/requests, signed with the
link secret: import.begin/batch/finish/abort for moving a product's users
in (EVENTS-3.0-PLAN §4), people.* for product admins (§8). sealLinkValue /
openLinkValue seal password hashes and TOTP secrets with a key derived
from the link secret; importIdsHash for the final check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:33:15 +02:00
joshua ac017395df Merge branch 'docs/events-3-first' 2026-11-19 12:50:28 +02:00
joshuaandClaude Opus 5.5 258f8b820d docs: plan for Cross Events 3.0 (sign-in through Accounts)
EVENTS-3.0-PLAN.md: User.accountId, sign-in through auth-client with a
one-time handoff to Events' own token, 2FA step-up for staff, the user
import into Accounts (hashes, authenticator secrets, consent, notices),
an admin-run move with 14 days' undo, and what Accounts 1.1.0, contracts
1.8.0 and Hub 2.5.0 need. Linked from the roadmap and handover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:37:28 +02:00
joshuaandClaude Opus 5.5 9985444937 docs: Events 3.0 (sign-in through Accounts) before the Website
Phases 4 and 5 swapped in ROADMAP-v3 (decision 38): Cross Events 3.0.0 is
phase 4, the Church Website phase 5. Phase 3 marked released; handover,
versions, README and the Accounts and Events 2.4 plans follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:32:48 +02:00
joshuaandClaude Opus 5.5 2fd88b1337 Merge branch 'feat/seed-demo-from-hub'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:53:56 +02:00
joshuaandClaude Opus 5.5 3e46d22bc6 docs: VERSIONS.md and HANDOVER for events@2.4.1, contracts@1.7.0, agent@1.2.0, Hub 2.4.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:43:21 +02:00
joshuaandClaude Opus 5.5 6ac17a6a62 Events 2.4.1: the default logo is the Cross Code logo, not Hope Family Church's
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:38:35 +02:00
joshuaandClaude Opus 5.5 f2a5df029a Demo data from the Hub: crosscode demo, the seed-demo job, set-demo fixes
- scripts: `crosscode demo <church> --profile … [--admin-email …]`: backup,
  set-demo.js as the site's user, reload, wait for /health.
- Contracts 1.7.0: the seed-demo job, DEMO_PROFILES, SEED_DEMO_MIN_AGENT.
- Agent 1.2.0: seed-demo → crosscode demo.
- Events 2.4.1: set-demo.js stops with a clear message when it can't read
  .env (was "client password must be a string", then a hang); keeps the
  oldest admin when the default one isn't on the site; --admin-email=.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:37:16 +02:00
joshuaandClaude Opus 5.5 126beaad70 docs: VERSIONS.md for accounts@1.0.1, contracts@1.6.0, Hub 2.3.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:26:30 +02:00
joshuaandClaude Opus 5.5 9e315f199c Merge branch 'fix/trust-proxy-checks'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:23:49 +02:00
joshuaandClaude Opus 5.5 fd8f6c28b0 Refuse a TRUST_PROXY the apps can't start with; Accounts reads loopback
A server configuration with TRUST_PROXY=TRUE made an Events install build for
minutes, then fail: Express threw "invalid IP address: TRUE" at startup.

- scripts/lib/envtpl.cjs: VALUE_RULES checked before any .env is written
  (exit 4, naming the value and the fix), for every release.
- Contracts 1.6.0: agent.checkEnvValue / agent.invalidValues, the same rules
  for the Hub.
- Accounts 1.0.1: TRUST_PROXY read as Events reads it; loopback used to
  turn proxy trust off.
- Docs: CHANGELOGs, WHATS-NEW, HANDOVER, AGENT-1.0-PLAN, ROLLOUT-1.0, READMEs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 10:23:49 +02:00
joshuaandClaude Opus 5.5 db2e544ed6 docs: VERSIONS.md, the latest version of everything and what's deployed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:23:36 +02:00
joshua ccd1cfff46 Merge branch 'fix/install-keeps-backend-logs' 2026-11-19 09:03:50 +02:00
joshuaandClaude Opus 5.5 7fd699a2fd Release the crosscode script fix: failed installs show their PM2 logs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:03:48 +02:00
joshuaandClaude Opus 5.5 6988b5ce7c Scripts: a failed install shows its PM2 apps' last log lines
Before removing what a failed install made, print each PM2 app's last
30 log lines, so the Hub's job log says why the backend didn't start
instead of only "/health didn't report 2.3.1 within 90s".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:44:38 +02:00
201 changed files with 16075 additions and 644 deletions
+159
View File
@@ -2,6 +2,165 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## 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).
Tested on Postgres 18 (both apps' migrations, `test:accounts` on real databases, the Events e2e
suite with the new sign-in spec); not VM tested yet.
- **Scripts:** `products/events.sh` installs and builds `packages/auth-client` (after contracts)
when the checkout's Events uses it, as 3.0.0 does.
- **Contracts 1.8.0:** `crosscode.identity-request/1` (product → Accounts at
`/api/accounts/v1/requests`): `import.begin` / `batch` / `finish` / `abort` and `people.*`;
`sealLinkValue` / `openLinkValue` in `/signing`.
- **Accounts 1.1.0:** takes the requests: moves Events' users in with their password hashes and
authenticator secrets, new recovery codes after the first 2FA sign-in, `people.*` for people a
product knows, `screen=signup`. Details in `apps/accounts/CHANGELOG.md`.
- **`@crosscode/auth-client` 1.1.0:** `request()`, `seal()`, `startSignIn(…, { signUp })`.
- **Events 3.0.0:** Settings → Sign-in (check, move, undo), sign-in and sign-out through Accounts,
Accounts' calls, admin actions through Accounts. Details in `apps/events/CHANGELOG.md` and
`apps/events/MIGRATING-TO-3.md`.
## events@2.4.1, contracts@1.7.0, agent@1.2.0, crosscode script - 2026-11-19
Demo data from the Hub, for installs marked as demo sites (Hub 2.4.0).
- **Scripts: `crosscode demo <church> --profile <small|events|ministry|multicampus>
[--admin-email <email>]`.** Takes a backup, loads the demo set as the site's user (who alone
can read its `.env`), then reloads Events and waits for `/health`. Stops before the data if the
backup fails, and doesn't reload after a failed seed.
- **Contracts 1.7.0:** the `seed-demo` job (`church`, `profile`, optional `adminEmail`; 15
minutes), `DEMO_PROFILES`, `SEED_DEMO_MIN_AGENT`.
- **Agent 1.2.0:** runs `seed-demo` jobs as `crosscode demo`. Older agents refuse them, so the
Hub checks the agent's version first.
- **Events 2.4.1:** `set-demo.js` says to run as the site's user instead of failing with "client
password must be a string" and hanging; keeps the site's oldest admin when the default isn't
there. The default logo (before a church uploads one) is the Cross Code logo, not Hope Family
Church's. Details in `apps/events/CHANGELOG.md`.
## accounts@1.0.1, contracts@1.6.0, crosscode script - 2026-11-19
A server configuration with `TRUST_PROXY=TRUE` made an Events install build for minutes, then
fail: the backend crashed at startup (`invalid IP address: TRUE`) and the install was removed.
- **Scripts: a value the app can't start with stops the install before the build.**
`lib/envtpl.cjs` checks values against `VALUE_RULES` (so far `TRUST_PROXY`: `loopback`, a hop
count, lowercase `true`/`false`, or proxy IPs/CIDRs) and exits 4 naming the value and the fix,
before any `.env` is written. The rules are in the script, so they apply to every release,
including ones from before them. On deploy, values already in a `.env` aren't checked.
- **Contracts 1.6.0:** `agent.checkEnvValue(name, value)` and `agent.invalidValues(values)`, the
same rules for the Hub (Hub 2.3.3 refuses a bad value when the configuration is saved and before
a job).
- **Accounts 1.0.1:** `TRUST_PROXY=loopback` turned proxy trust off; it's now read as Events reads
it. Details in `apps/accounts/CHANGELOG.md`.
## crosscode script - 2026-11-19 (no tag: servers run `main`)
- **Scripts: a failed install says why its apps didn't start.** Before removing what a failed
install made, `crosscode install` / `crosscode add` print each PM2 app's last 30 log lines. The
logs used to go with the apps, so the Hub only showed "/health didn't report 2.3.1 within 90s
(last answer: none)" and the reason was lost.
## agent@1.1.1 - 2026-11-18
- **Stats keep going while a job runs.** The agent sent stats and polled in one loop, so during
+1 -1
View File
@@ -9,7 +9,7 @@ things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
| `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 4) |
| `apps/website` | Church Website | Placeholder (phase 5) |
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
+2
View File
@@ -0,0 +1,2 @@
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
/ecosystem.config.cjs
+164
View File
@@ -1,5 +1,169 @@
# Changelog — Accounts
## [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.
### Added
- **`POST /api/accounts/v1/requests`** (`crosscode.identity-request/1`), signed with the link's
secret: what a linked product asks of Accounts. A request id seen before gets its first answer.
- **Moving a product's users in** (`import.begin` / `batch` / `finish` / `abort`, Cross Events
only): each person keeps their Events id as their `sub`, their bcrypt or Argon2id password hash,
2FA method and authenticator secret (sealed with the link's secret on the way, encrypted with
Accounts' key at rest), lockout, news consent and its history, notice acceptance, last sign-in
and status; ticked Events admins become Accounts admins. An email that already has an account is
**linked** (that account and its password stay). A check (`check: true`) writes nothing.
`import.finish` checks every sub the product relies on is an account here, not deleted, and
known to that product, and lists the ones that aren't. Events' privacy notice versions are
taken when Accounts has published none; an empty church name and colour are filled from Events.
- **New recovery codes after the first sign-in** for people moved in with 2FA (their Events codes
can't move): shown once after the second step, whatever step comes next.
- **`people.*`**: `ensure` (find or make an account; a new one gets a "choose your password" email
whose link ends on the product), `update`, `resetTwoFactor`, `unlock`, `setActive`, `newsOff`.
Only for people the product knows (moved in, added, or signed in through it), never an Accounts
admin's 2FA or status, and audited with the product and the product admin's `sub`.
- **`screen=signup`** on an authorization request opens the sign-in page on "Create an account"
(`startSignIn(…, { signUp: true })` in `@crosscode/auth-client`).
### Changed
- Setting a password from an emailed link also confirms the email address.
## [1.0.1] - 2026-11-19
### Fixed
- **`TRUST_PROXY=loopback` turned proxy trust off.** Accounts read `TRUST_PROXY` as true/false, so
anything but `true`, including the `loopback` the Hub suggests behind frp, meant off: rate
limiting and the audit log saw every visitor as `127.0.0.1`, and oidc-provider ignored
`X-Forwarded-Proto`. It's now read as Events reads it: `loopback`, a hop count, proxy IP
addresses/CIDRs separated by commas, or `true`/`false` in any case (`true` is one hop, as
before). Unset is still one hop in production.
## [1.0.0] - 2026-11-18
The first release (docs/ACCOUNTS-1.0-PLAN.md), with Hub 2.3.0 and agent 1.1.0. Released before the
+54
View File
@@ -3,6 +3,60 @@
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.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,
with their passwords and authenticator apps, so nobody has to reset anything. People who use
two-step sign-in get new recovery codes the first time they sign in.
- Cross Events admins can add people, fix their details, unlock them and reset two-step sign-in
without leaving Cross Events.
## 1.0.1
- **Fix:** sign-in limits and the activity log now see each visitor's own address on servers
behind the Cross Code proxy, instead of the proxy's.
## 1.0.0
- **One sign-in for all your church's sites and apps.** People sign in once with their own account
+1
View File
@@ -4,3 +4,4 @@ src/generated/
.env
uploads/
exports/
/backups/
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.0.0",
"version": "1.6.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
@@ -22,6 +22,7 @@
"@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,50 @@
-- Accounts 1.1.0 (docs/EVENTS-3.0-PLAN.md §8): moving a product's users in, and its people.* requests.
-- AlterTable
ALTER TABLE "Account" ADD COLUMN "recoveryCodesNeeded" BOOLEAN NOT NULL DEFAULT false;
-- AlterTable
ALTER TABLE "EmailToken" ADD COLUMN "returnUrl" TEXT;
-- AlterTable
ALTER TABLE "ProductLink" ADD COLUMN "importStartedAt" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "ProductPerson" (
"id" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"via" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ProductPerson_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ProductRequest" (
"requestId" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"reply" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ProductRequest_pkey" PRIMARY KEY ("requestId")
);
-- CreateIndex
CREATE UNIQUE INDEX "ProductPerson_linkId_accountId_key" ON "ProductPerson"("linkId", "accountId");
-- CreateIndex
CREATE INDEX "ProductPerson_accountId_idx" ON "ProductPerson"("accountId");
-- CreateIndex
CREATE INDEX "ProductRequest_createdAt_idx" ON "ProductRequest"("createdAt");
-- AddForeignKey
ALTER TABLE "ProductPerson" ADD CONSTRAINT "ProductPerson_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ProductPerson" ADD CONSTRAINT "ProductPerson_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ProductRequest" ADD CONSTRAINT "ProductRequest_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
+47 -10
View File
@@ -55,6 +55,9 @@ model Account {
lastSignInAt DateTime?
deactivatedAt DateTime?
anonymisedAt DateTime?
// 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)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -65,6 +68,7 @@ model Account {
consentChanges ConsentChange[]
exports DataExport[]
deletionRequests DeletionRequest[]
products ProductPerson[]
@@index([status])
}
@@ -107,6 +111,8 @@ model EmailToken {
tokenHash String @unique
// The sign-in the link belongs to, so it carries on to the product afterwards (§5).
interactionUid String?
// 1.1.0: a "set your password" link a product asked for (people.ensure) ends on that product.
returnUrl String?
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
@@ -195,16 +201,47 @@ 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?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries Delivery[]
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[]
}
// 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it).
// A product's people.* requests only reach these.
model ProductPerson {
id String @id @default(uuid())
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
via String // import | ensure | sign_in
createdAt DateTime @default(now())
@@unique([linkId, accountId])
@@index([accountId])
}
// 1.1.0: crosscode.identity-request/1 requests already handled, so a retry gets the same answer.
model ProductRequest {
requestId String @id
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
type String
reply Json
createdAt DateTime @default(now())
@@index([createdAt])
}
model LinkNonce {
+23 -6
View File
@@ -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;
@@ -100,18 +102,33 @@ 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 });
if (method === 'whatsapp' && a.phone) {
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);
}
}
return { codeHash: hashToken(code), sentTo: maskedTarget(a, method) };
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 && (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';
}
}
+108 -5
View File
@@ -1,12 +1,14 @@
/**
* 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 { currentSession } from '../oidc/sessions.js';
@@ -16,10 +18,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 +144,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) => {
@@ -196,7 +201,24 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
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.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 +250,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) => {
+4 -1
View File
@@ -6,6 +6,7 @@
* /api/oidc/… the OpenID Connect provider (discovery, auth, token, …)
* /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/… the pages' API (sign-in steps, account, admin, setup)
*/
import express from 'express';
@@ -17,6 +18,7 @@ import { interactionRouter, selfRouter } from './interaction/routes.js';
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 { setupRouter } from './setup/routes.js';
import { health } from './hub/client.js';
import { appVersion } from './lib/version.js';
@@ -24,7 +26,7 @@ import { appVersion } from './lib/version.js';
export function createApp(ctx: Ctx, provider: Provider) {
const app = express();
app.disable('x-powered-by');
if (ctx.config.trustProxy) app.set('trust proxy', 1);
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
@@ -46,6 +48,7 @@ export function createApp(ctx: Ctx, provider: Provider) {
// The provider parses its own bodies: mounted before express.json.
app.use('/api/oidc', provider.callback());
app.use('/api/self', selfRouter(ctx));
app.use('/api', requestsRouter(ctx, provider));
app.use('/api', publicRouter(ctx));
const v2 = express.Router();
@@ -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 };
}
+2 -1
View File
@@ -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,
+19 -4
View File
@@ -18,7 +18,7 @@ import type { Account, PendingSignIn } from '../generated/prisma/client.js';
import {
codeMatches, emailProblem, isLocked, maskedTarget, normaliseEmail, normalisePhone, sendCode, setNewsConsent, signInFailed, signInSucceeded, CODE_MINUTES,
} from '../accounts/service.js';
import { accessAfterTwoFactor, confirmTwoFactorSetup, startTwoFactorSetup, useRecoveryCode, verifyTotp } from '../accounts/twoFactor.js';
import { accessAfterTwoFactor, confirmTwoFactorSetup, replaceRecoveryCodes, startTwoFactorSetup, useRecoveryCode, verifyTotp } from '../accounts/twoFactor.js';
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';
@@ -94,22 +94,28 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
signupEnabled: await ctx.settings.bool('signup_enabled', true),
mfaRequested: mfaRequested(details),
loginHint: typeof details.params.login_hint === 'string' ? details.params.login_hint : null,
// 1.1.0: a product's "Create an account" link opens on sign-up (`screen=signup`).
screen: details.params.screen === 'signup' ? 'signup' : 'signin',
};
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 ? ['whatsapp'] : [])];
extra.why = a.role === 'admin' ? 'admin' : 'product';
}
if (stage === 'notice') {
@@ -209,7 +215,16 @@ export async function twoFactor(ctx: Ctx, pending: PendingSignIn, input: { code?
} else {
await checkCode(ctx, pending, input.code);
}
return save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 });
const next = await save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 });
// Moved in from a product without its recovery codes (EVENTS-3.0-PLAN decision 2): new ones now,
// shown once on the next page.
if (a.recoveryCodesNeeded) {
const recoveryCodes = await replaceRecoveryCodes(ctx, a.id);
await ctx.db.account.update({ where: { id: a.id }, data: { recoveryCodesNeeded: false } });
await loginEvent(ctx, a.id, 'recovery_codes_replaced', req, { detail: { by: 'move' } });
return { pending: next, recoveryCodes };
}
return { pending: next, recoveryCodes: null as string[] | null };
}
export async function setupStart(ctx: Ctx, pending: PendingSignIn, method: unknown) {
+20 -10
View File
@@ -8,13 +8,16 @@ 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';
import { SELF_CALLBACK, SELF_CLIENT_ID } from '../oidc/clients.js';
import { issuerOf } from '../oidc/provider.js';
import * as flow from './flow.js';
import { signedInThrough } from '../links/requests.js';
const RESET_MINUTES = 60;
@@ -39,7 +42,11 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const state = await flow.describe(ctx, details, pending);
if (state.stage !== 'done') return { ...state, ...extra };
const redirectTo = await provider.interactionResult(req, res, flow.loginResult(pending), { mergeWithLastSubmission: false });
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId: String(details.params.client_id ?? '') || null, detail: { amr: pending.amr } });
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 };
}
@@ -61,7 +68,10 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
r.post('/interaction/:uid/password', limit(20), step(async (req, _res, p) => { await flow.submitPassword(ctx, p, req.body ?? {}, req); }));
r.post('/interaction/:uid/signup', limit(10, 60), step(async (req, _res, p) => { await flow.signUp(ctx, p, req.body ?? {}); }));
r.post('/interaction/:uid/verify-email', limit(20), step(async (req, _res, p) => { await flow.verifyEmail(ctx, p, req.body?.code); }));
r.post('/interaction/:uid/two-factor', limit(20), step(async (req, _res, p) => { await flow.twoFactor(ctx, p, req.body ?? {}, req); }));
r.post('/interaction/:uid/two-factor', limit(20), step(async (req, _res, p) => {
const { recoveryCodes } = await flow.twoFactor(ctx, p, req.body ?? {}, req);
return recoveryCodes ? { recoveryCodes } : undefined;
}));
r.post('/interaction/:uid/resend', limit(10), step(async (_req, _res, p) => { await flow.resendCode(ctx, p); }));
r.post('/interaction/:uid/two-factor/setup', limit(10), handle(async (req, res) => {
const { pending } = await load(req, res);
@@ -82,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).
@@ -89,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 };
}));
@@ -104,12 +112,14 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
if (!row || row.purpose !== 'reset_password' || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used. Ask for a new one.');
const problem = passwordProblem(req.body?.password);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem });
await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null } });
// Setting a password from an emailed link also proves the address.
await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null, emailVerified: true } });
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await ctx.db.emailToken.deleteMany({ where: { accountId: row.accountId, purpose: 'reset_password', usedAt: null } });
await loginEvent(ctx, row.accountId, 'password_reset', req);
// Back to the sign-in it started from, if this browser still has it (§5).
return { reset: true, uid: row.interactionUid };
// A "set your password" link a product asked for (people.ensure) ends on that product, which signs them in.
return { reset: true, uid: row.interactionUid, returnUrl: row.returnUrl ?? null };
}));
return r;
+274 -25
View File
@@ -1,54 +1,303 @@
/**
* 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';
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] = await Promise.all([
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
deleteExpired(ctx),
ctx.db.pendingSignIn.deleteMany({ where: { expiresAt: { lt: now } } }),
ctx.db.emailToken.deleteMany({ where: { expiresAt: { lt: new Date(now.getTime() - 7 * 24 * 3600e3) } } }),
ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - 3600e3) } } }),
forgetOldRequests(ctx),
]);
return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count };
return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count, requests: requests.count };
},
},
];
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) ?? [],
};
}),
};
}
+33 -2
View File
@@ -9,8 +9,10 @@ export type Config = {
/** Encrypts secrets at rest and signs cookies. Generated on the server, never sent anywhere. */
secret: string;
production: boolean;
/** Behind nginx/frp: trust X-Forwarded-* (as Events' TRUST_PROXY). */
/** Behind nginx/frp: trust X-Forwarded-* (oidc-provider's `proxy`). */
trustProxy: boolean;
/** Express's "trust proxy" (TRUST_PROXY, read as Events reads it), or false when off. */
trustProxySetting: TrustProxy;
hubUrl: string;
hubLicenceKey: string | null;
hubPublicKey: string | null;
@@ -18,24 +20,50 @@ 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');
export type TrustProxy = false | number | string | string[];
/**
* TRUST_PROXY as Express's "trust proxy": `loopback` (behind frp, the default the Hub suggests),
* a hop count, IP addresses/CIDRs separated by commas, `true` (one hop: never "trust everyone") or
* `false`. Unset: one hop in production, off otherwise. Before 1.0.1 anything but `true` meant
* off, so `loopback` turned it off.
*/
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
const raw = (v ?? '').trim();
if (raw === '') return production ? 1 : false;
const lower = raw.toLowerCase();
if (lower === 'true') return 1;
if (lower === 'false') return false;
if (/^\d+$/.test(raw)) return Number(raw) || false;
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
}
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
const publicUrl = String(env.ACCOUNTS_URL || env.PUBLIC_URL || 'http://localhost:3200').replace(/\/+$/, '');
const production = env.NODE_ENV === 'production';
const secret = env.ACCOUNTS_SECRET || '';
const trustProxySetting = trustProxyFrom(env.TRUST_PROXY, production);
if (production && secret.length < 32) throw new Error('ACCOUNTS_SECRET must be set (at least 32 characters) in production.');
return {
publicUrl,
port: Number(env.PORT || 5200),
secret: secret || 'development-only-secret-change-me-0123456789',
production,
trustProxy: bool(env.TRUST_PROXY, production),
trustProxy: trustProxySetting !== false,
trustProxySetting,
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
@@ -45,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,
};
}
+225
View File
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
/** 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(' &bull; ');
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)}&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;</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 };
}
+87 -17
View File
@@ -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)];
+1 -1
View File
@@ -9,7 +9,7 @@ export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_i
/** The settings an admin may read and change through the generic settings API. */
export const ADMIN_SETTINGS = new Set([
'signup_enabled', 'two_factor_required_for_admins', 'session_days',
'signup_enabled', 'two_factor_required_for_admins', 'session_days', 'signin_notices',
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
'wawp_access_token', 'wawp_instance_id',
]);
+453
View File
@@ -0,0 +1,453 @@
/**
* What a linked product asks of Accounts (`crosscode.identity-request/1`, contracts 1.8.0,
* docs/EVENTS-3.0-PLAN.md §4 and §8), at `POST /api/accounts/v1/requests`, signed with the link's
* secret (`LINK_HEADERS`, the sender header carrying the product's install id):
*
* - `import.*`: moving the product's users in (Cross Events 3.0) with their password hashes and
* authenticator secrets, which arrive sealed with the link's secret. Only Events imports, and
* only between `import.begin` and `import.finish` / `import.abort`.
* - `people.*`: what the product's admins can do to an account from the product. Only for people
* the product knows (`ProductPerson`: imported, added or signed in through it).
*
* A request id seen before gets the first answer again, so a product can retry safely.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import type Provider from 'oidc-provider';
import {
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
} from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
import 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, profileOf, setNewsConsent } from '../accounts/service.js';
import { turnOff } from '../accounts/twoFactor.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { anonymise } from '../privacy/deletion.js';
/** 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) {
super(message);
}
}
/** Products that may move their users in. */
const IMPORTERS = new Set(['events']);
const SET_PASSWORD_DAYS = 7;
const KEEP_REQUESTS_DAYS = 30;
const reply = <T extends object>(body: T) => ({ schema: IDENTITY_REQUEST_SCHEMA, ...body });
const header = (req: Request, name: string) => {
const v = req.headers[name];
return Array.isArray(v) ? v[0] : v;
};
/** The link the request came from, after checking its signature. */
async function linkFor(ctx: Ctx, req: Request, raw: Buffer): Promise<{ link: ProductLink; secret: string }> {
const sender = header(req, LINK_HEADERS.sender);
const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: String(sender) } }) : null;
if (!link) throw new RequestError('That product isn\'t connected to Accounts.', 'NOT_LINKED', 403);
const secret = ctx.secrets.decrypt(link.secret);
const check = verify({ secret, timestamp: header(req, LINK_HEADERS.timestamp), signature: header(req, LINK_HEADERS.signature), rawBody: raw, now: ctx.now() });
if (!check.ok) throw new RequestError(check.code === 'STALE_REQUEST' ? 'The request is too old, or a clock is wrong.' : 'The request isn\'t signed with this link\'s secret.', check.code, 401);
return { link, secret };
}
async function knows(ctx: Ctx, linkId: string, accountId: string, via: string, opts: { upgrade?: boolean } = {}) {
const existing = await ctx.db.productPerson.findFirst({ where: { linkId, accountId } });
if (!existing) await ctx.db.productPerson.create({ data: { linkId, accountId, via, createdAt: ctx.now() } });
else if (opts.upgrade && existing.via !== via) await ctx.db.productPerson.update({ where: { id: existing.id }, data: { via } });
}
/** Records that a product signed someone in (so its people.* requests reach them). */
export async function signedInThrough(ctx: Ctx, clientId: string | null, accountId: string | null) {
if (!clientId || !accountId) return;
const link = await ctx.db.productLink.findUnique({ where: { installId: clientId } });
if (link) await knows(ctx, link.installId, accountId, 'sign_in').catch(() => {});
}
async function knownAccount(ctx: Ctx, link: ProductLink, sub: string) {
const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: sub } });
const a = known ? await ctx.db.account.findUnique({ where: { id: sub } }) : null;
if (!a || a.status === 'deleted') throw new RequestError('That person isn\'t known to Accounts through this product.', 'UNKNOWN_PERSON', 404);
return a;
}
const logRequest = (ctx: Ctx, link: ProductLink, r: IdentityRequest, action: string, targetId: string | null, req: Request, metadata: object = {}) =>
audit(ctx, { actorId: r.actor, actorRole: 'linked_product', action, targetType: targetId ? 'account' : 'product_link', targetId: targetId ?? link.installId, metadata: { product: link.product, installId: link.installId, ...metadata }, ip: clientIp(req) });
// ─── import.* ────────────────────────────────────────────────────────────────
const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/;
function opened(secret: string, sealed: string | null, what: string): string | null {
if (sealed === null) return null;
try {
return openLinkValue(secret, sealed);
} catch {
throw new RequestError(`A ${what} couldn't be opened with this link's secret.`, 'INVALID_REQUEST', 400);
}
}
/** What happens to one person; writes only when `write`. */
async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportPerson, write: boolean): Promise<ImportResult> {
const email = normaliseEmail(p.email);
if (emailProblem(email)) return { id: p.id, outcome: 'refused', sub: null, reason: 'The email address isn\'t valid.' };
const passwordHash = opened(secret, p.passwordHash, 'password hash');
if (passwordHash !== null && !HASH.test(passwordHash)) return { id: p.id, outcome: 'refused', sub: null, reason: 'The password hash isn\'t bcrypt or Argon2.' };
const totp = p.twoFactor === 'totp' ? opened(secret, p.totpSecret, 'authenticator secret') : null;
if (p.twoFactor === 'totp' && !totp) return { id: p.id, outcome: 'refused', sub: null, reason: 'An authenticator app is on but its secret is missing.' };
const byId = await ctx.db.account.findUnique({ where: { id: p.id } });
const byEmail = await ctx.db.account.findUnique({ where: { email } });
// Already moved by this product (a move run again): bring it up to date.
if (byId) {
const mine = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: byId.id, via: 'import' } });
if (!mine) return { id: p.id, outcome: 'refused', sub: null, reason: 'Accounts already has a different account with this id.' };
if (byEmail && byEmail.id !== byId.id) return { id: p.id, outcome: 'refused', sub: null, reason: 'Another account has this email address.' };
if (write) await ctx.db.account.update({ where: { id: byId.id }, data: fields(ctx, p, email, passwordHash, totp) });
return { id: p.id, outcome: 'updated', sub: byId.id, reason: null };
}
// The email already has an account (made before the move): link to it, change nothing.
if (byEmail) {
if (write) await knows(ctx, link.installId, byEmail.id, 'import', { upgrade: true });
return { id: p.id, outcome: 'linked', sub: byEmail.id, reason: null };
}
if (write) {
const a = await ctx.db.account.create({ data: { id: p.id, ...fields(ctx, p, email, passwordHash, totp), createdAt: new Date(p.createdAt) } });
for (const n of p.noticeAcceptances) await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: n.version, acceptedAt: new Date(n.acceptedAt) } });
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 } });
}
return { id: p.id, outcome: 'created', sub: p.id, reason: null };
}
function fields(ctx: Ctx, p: ImportPerson, email: string, passwordHash: string | null, totp: string | null) {
return {
name: p.name,
email,
emailVerified: p.emailVerified,
phone: p.phone,
passwordHash,
twoFactorMethod: p.twoFactor,
totpSecret: totp ? ctx.secrets.encrypt(totp) : null,
totpLastStep: totp ? p.totpLastStep : null,
// Their old recovery codes can't move (EVENTS-3.0-PLAN decision 2): new ones after the next sign-in.
recoveryCodesNeeded: p.twoFactor !== null,
failedSignIns: p.failedSignIns,
lockedUntil: p.lockedUntil ? new Date(p.lockedUntil) : null,
newsEmail: p.news.email,
newsWhatsApp: p.news.whatsapp,
newsAskedAt: p.newsAskedAt ? new Date(p.newsAskedAt) : null,
noticeVersionAccepted: p.noticeVersionAccepted,
lastSignInAt: p.lastSignInAt ? new Date(p.lastSignInAt) : null,
status: p.status,
deactivatedAt: p.status === 'deactivated' ? ctx.now() : null,
role: p.admin ? ('admin' as const) : ('member' as const),
};
}
async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: string, r: IdentityRequest, req: Request): Promise<object> {
switch (r.type) {
case 'import.begin': {
if (!IMPORTERS.has(link.product)) throw new RequestError('Only Cross Events moves its users into Accounts.', 'WRONG_PRODUCT', 403);
const own = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'asc' } });
const noticesTaken = own.length === 0;
if (!r.check) {
if (noticesTaken) {
for (const n of r.notices.filter((x) => x.version > BUILT_IN_VERSION)) {
await ctx.db.privacyNotice.create({ data: { version: n.version, title: n.title, body: n.body, publishedAt: new Date(n.publishedAt), publishedById: null } });
}
}
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 });
}
return reply({ noticesTaken, accountsNoticeVersions: own.map((n) => n.version), accountsVersion: appVersion() });
}
case 'import.batch': {
if (!IMPORTERS.has(link.product)) throw new RequestError('Only Cross Events moves its users into Accounts.', 'WRONG_PRODUCT', 403);
if (!r.check && !link.importStartedAt) throw new RequestError('Start the move first (import.begin).', 'NOT_MOVING', 409);
const seen = new Set<string>();
const results: ImportResult[] = [];
for (const p of r.people) {
const email = normaliseEmail(p.email);
if (seen.has(email)) {
results.push({ id: p.id, outcome: 'refused', sub: null, reason: 'The same email address is twice in this move.' });
continue;
}
seen.add(email);
results.push(await importOne(ctx, link, secret, p, !r.check));
}
return reply({ results });
}
case 'import.finish': {
if (!link.importStartedAt) throw new RequestError('There\'s no move under way.', 'NOT_MOVING', 409);
// Every account the product relies on must be here, not deleted, and known to it.
const wanted = [...new Set(r.subs)];
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: wanted } } })).map((x) => x.accountId));
const live = new Set((await ctx.db.account.findMany({ where: { id: { in: wanted }, status: { not: 'deleted' } }, select: { id: true } })).map((x) => x.id as string));
const missing = wanted.filter((s) => !known.has(s) || !live.has(s));
const matched = missing.length === 0;
if (matched) await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } });
await logRequest(ctx, link, r, matched ? 'import_finished' : 'import_mismatch', null, req, { count: wanted.length - missing.length, expected: wanted.length });
return reply({ matched, count: wanted.length - missing.length, missing: missing.slice(0, 100) });
}
case 'import.abort': {
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } });
await logRequest(ctx, link, r, 'import_aborted', null, req);
return reply({ ok: true as const });
}
case 'people.ensure': {
const email = normaliseEmail(r.email);
const existing = await ctx.db.account.findUnique({ where: { email } });
if (existing && existing.status === 'deleted') throw new RequestError('That email address belonged to a deleted account.', 'NOT_ALLOWED', 409);
if (existing) {
await knows(ctx, link.installId, existing.id, 'ensure');
await logRequest(ctx, link, r, 'person_linked_by_product', existing.id, req);
return reply({ sub: existing.id, created: false });
}
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');
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) } });
// 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, { emailSent });
return reply({ sub: a.id, created: true, emailSent });
}
case 'people.update': {
const a = await knownAccount(ctx, link, r.sub);
const data: Record<string, unknown> = {};
if (r.name !== undefined) data.name = r.name;
if (r.phone !== undefined) { data.phone = r.phone; if (r.phone !== a.phone) data.phoneVerified = false; }
if (r.email !== undefined) {
const email = normaliseEmail(r.email);
if (email !== a.email) {
const other = await ctx.db.account.findUnique({ where: { email } });
if (other) throw new RequestError('Another account has that email address.', 'EMAIL_TAKEN', 409);
data.email = email;
data.emailVerified = false;
}
}
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);
}
await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) });
return reply({ ok: true as const });
}
case 'people.resetTwoFactor': {
const a = await knownAccount(ctx, link, r.sub);
if (a.role === 'admin') throw new RequestError('An Accounts admin\'s two-factor sign-in can only be reset in Accounts.', 'NOT_ALLOWED', 403);
await turnOff(ctx, a.id);
await ctx.db.account.update({ where: { id: a.id }, data: { recoveryCodesNeeded: false } });
await signOutEverywhere(ctx, provider, a.id);
await loginEvent(ctx, a.id, 'two_factor_off', req, { clientId: link.installId, detail: { by: 'product' } });
await logRequest(ctx, link, r, 'two_factor_reset_by_product', a.id, req);
return reply({ ok: true as const });
}
case 'people.unlock': {
const a = await knownAccount(ctx, link, r.sub);
await ctx.db.account.update({ where: { id: a.id }, data: { lockedUntil: null, failedSignIns: 0 } });
await logRequest(ctx, link, r, 'account_unlocked_by_product', a.id, req);
return reply({ ok: true as const });
}
case 'people.setActive': {
const a = await knownAccount(ctx, link, r.sub);
if (a.role === 'admin' && !r.active) throw new RequestError('An Accounts admin can only be deactivated in Accounts.', 'NOT_ALLOWED', 403);
await ctx.db.account.update({ where: { id: a.id }, data: r.active ? { status: 'active', deactivatedAt: null } : { status: 'deactivated', deactivatedAt: ctx.now() } });
if (!r.active) await signOutEverywhere(ctx, provider, a.id);
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 '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 };
}
}
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 };
if (await setNewsConsent(ctx, a, off, 'product_unsubscribe')) await profileChanged(ctx, a.id);
await logRequest(ctx, link, r, 'news_off_by_product', a.id, req, { channel: r.channel });
return reply({ ok: true as const });
}
}
}
export function requestsRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
r.post(ACCOUNTS_REQUEST_PATH.replace(/^\/api/, ''), limit(600), express.raw({ type: '*/*', limit: '4mb' }), async (req: Request, res: Response) => {
try {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const { link, secret } = await linkFor(ctx, req, raw);
let body: unknown;
try {
body = JSON.parse(raw.toString('utf8'));
} catch {
throw new RequestError('The body must be JSON.', 'INVALID_REQUEST');
}
const parsed = identityRequestSchema.safeParse(body);
if (!parsed.success) throw new RequestError(`Not a crosscode.identity-request/1 request: ${parsed.error.issues[0]?.path.join('.') || ''} ${parsed.error.issues[0]?.message ?? ''}`.trim(), 'INVALID_REQUEST');
const request = parsed.data;
const before = await ctx.db.productRequest.findUnique({ where: { requestId: request.requestId } });
if (before) {
if (before.linkId !== link.installId) throw new RequestError('That request id was used by another product.', 'INVALID_REQUEST', 409);
return res.json(before.reply);
}
const out = await handle(ctx, provider, link, secret, request, req);
// Checks write nothing, so they needn't be remembered.
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
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(() => {});
}
return res.json(out);
} catch (e) {
if (e instanceof RequestError) return res.status(e.status).json({ message: e.message, code: e.code });
console.error('[requests]', e);
return res.status(500).json({ message: 'Something went wrong.', code: 'SERVER_ERROR' });
}
});
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 },
};
}
/** 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) } } });
}
export const newRequestId = () => crypto.randomUUID();
+22 -2
View File
@@ -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,6 +17,13 @@ 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';
/** 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 {
@@ -44,6 +52,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;
@@ -74,7 +94,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 +106,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);
@@ -68,6 +68,8 @@ export async function createProvider(ctx: Ctx): Promise<Provider> {
adapter: adapterFor(ctx),
clients: [selfClient(ctx)],
extraClientMetadata: { properties: ['crosscode.product'] },
// 1.1.0: `screen=signup` opens the sign-in page on "Create an account".
extraParams: ['screen'],
clientDefaults: { id_token_signed_response_alg: 'ES256', grant_types: ['authorization_code'], response_types: ['code'], token_endpoint_auth_method: 'client_secret_basic' },
findAccount: async (_k, sub) => {
const a = await ctx.db.account.findUnique({ where: { id: sub } });
+2 -1
View File
@@ -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;
@@ -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;
}
+68 -7
View File
@@ -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,
};
}
+122
View File
@@ -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,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 &lt;Church&gt; &amp; 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"'), '&quot;x&quot;');
});
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>/);
});
});
+23
View File
@@ -10,6 +10,29 @@ import { Secrets } from '../src/lib/crypto.js';
import { stateFor, type LicenceClaims } from '../src/hub/licence.js';
import { normalisePhone } from '../src/accounts/service.js';
import { waNumber } from '../src/lib/messages.js';
import { loadConfig, trustProxyFrom } from '../src/lib/config.js';
describe('TRUST_PROXY', () => {
test('read as Events reads it: loopback behind frp is on, not off', () => {
assert.equal(trustProxyFrom('loopback', true), 'loopback');
assert.deepEqual(trustProxyFrom('loopback, 203.0.113.10', true), ['loopback', '203.0.113.10']);
assert.equal(trustProxyFrom('2', true), 2);
assert.equal(trustProxyFrom('TRUE', true), 1);
assert.equal(trustProxyFrom('true', false), 1);
assert.equal(trustProxyFrom('false', true), false);
assert.equal(trustProxyFrom('0', true), false);
assert.equal(trustProxyFrom(undefined, true), 1);
assert.equal(trustProxyFrom('', false), false);
});
test('oidc-provider trusts the proxy whenever Express does', () => {
const on = loadConfig({ NODE_ENV: 'test', TRUST_PROXY: 'loopback' });
assert.equal(on.trustProxy, true);
assert.equal(on.trustProxySetting, 'loopback');
const off = loadConfig({ NODE_ENV: 'test', TRUST_PROXY: 'false' });
assert.equal(off.trustProxy, false);
});
});
describe('passwords', () => {
test('Argon2id hashes verify, wrong passwords don\'t', async () => {
@@ -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');
});
});
@@ -0,0 +1,237 @@
// What a linked product asks of Accounts (crosscode.identity-request/1, contracts 1.8.0,
// docs/EVENTS-3.0-PLAN.md §4 and §8): moving Cross Events' users in with their passwords and
// authenticator apps, and the people.* requests an Events admin makes.
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { after, before, describe, test } from 'node:test';
import bcrypt from 'bcryptjs';
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, type ImportPerson } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
import { codeAt, generateSecret } from '../src/lib/totp.js';
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
let h: Harness;
let eventsSecret: string;
before(async () => {
h = await startHarness();
eventsSecret = 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(eventsSecret), connectedAt: new Date() },
});
});
after(async () => { await h.close(); });
/** Sends a request as a product (Events unless said otherwise). */
async function ask(body: Record<string, unknown>, opts: { from?: string; secret?: string; requestId?: string } = {}) {
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: opts.requestId ?? crypto.randomUUID(), actor: null, ...body });
const headers = signedHeaders(LINK_HEADERS, { senderId: opts.from ?? EVENTS_ID, secret: opts.secret ?? eventsSecret, 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> };
}
function person(over: Partial<ImportPerson> = {}): ImportPerson {
return {
id: crypto.randomUUID(), name: 'Moved Person', email: `${crypto.randomUUID().slice(0, 8)}@hope.test`, emailVerified: true, phone: null,
passwordHash: null, twoFactor: null, totpSecret: null, totpLastStep: null, failedSignIns: 0, lockedUntil: null,
news: { email: true, whatsapp: false }, newsAskedAt: '2026-01-01T00:00:00.000Z', noticeVersionAccepted: 1,
noticeAcceptances: [{ version: 1, acceptedAt: '2026-01-01T00:00:00.000Z' }], consentChanges: [{ channel: 'email', granted: true, at: '2026-01-01T00:00:00.000Z' }],
lastSignInAt: '2026-11-01T00:00:00.000Z', status: 'active', admin: false, createdAt: '2025-01-01T00:00:00.000Z', ...over,
};
}
const begin = (check = false) => ask({ type: 'import.begin', check, notices: [], church: { name: null, primaryColour: null } });
describe('moving Cross Events\' users in', () => {
test('a batch is refused before import.begin, and a check writes nothing', async () => {
const p = person();
const refused = await ask({ type: 'import.batch', check: false, people: [p] });
assert.equal(refused.status, 409);
assert.equal(refused.body.code, 'NOT_MOVING');
const check = await ask({ type: 'import.batch', check: true, people: [p] });
assert.equal(check.status, 200, JSON.stringify(check.body));
assert.equal((check.body.results as { outcome: string }[])[0]!.outcome, 'created');
assert.equal(await h.db.account.findUnique({ where: { id: p.id } }), null);
});
test('people sign in with their old bcrypt password and authenticator app, then get new recovery codes', async () => {
const totp = generateSecret();
const thandi = person({ email: 'Thandi.Moved@Hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Old-events-pass1', 4)), twoFactor: 'totp', totpSecret: sealLinkValue(eventsSecret, totp), totpLastStep: 1 });
const sipho = person({ email: 'sipho.moved@hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Sipho-pass-123', 4)) });
assert.equal((await begin()).status, 200);
const batch = await ask({ type: 'import.batch', check: false, people: [thandi, sipho] });
assert.equal(batch.status, 200, JSON.stringify(batch.body));
assert.deepEqual((batch.body.results as { outcome: string }[]).map((r) => r.outcome), ['created', 'created']);
// The sub is Events' user id; the secret is stored encrypted with Accounts' own key.
const a = (await h.db.account.findUnique({ where: { id: thandi.id } }))!;
assert.equal(a.email, 'thandi.moved@hope.test');
assert.notEqual(a.totpSecret, totp);
assert.equal(a.recoveryCodesNeeded, true);
assert.equal((await h.db.consentChange.findMany({ where: { accountId: thandi.id } }))[0]!.source, 'events_import');
const browser = new Browser();
const r = await h.signIn(browser, 'thandi.moved@hope.test', 'Old-events-pass1', '/events/camp/register');
assert.ok('pending' in r, 'asks for the authenticator');
assert.equal(r.pending.stage, 'two_factor');
const done = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: codeAt(totp, Math.floor(Date.now() / 30000)) });
assert.equal(done.status, 200, JSON.stringify(done.body));
assert.equal((done.body.recoveryCodes as string[]).length, 10, 'new recovery codes, shown once');
assert.equal((await h.db.account.findUnique({ where: { id: thandi.id } }))!.recoveryCodesNeeded, false);
const back = await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/api/auth/callback');
const signed = await h.finishSignIn(back.url, r.started);
assert.equal(signed.claims.sub, thandi.id);
assert.equal(signed.returnTo, '/events/camp/register');
// bcrypt is replaced with Argon2id at the first sign-in.
assert.match(String((await h.db.account.findUnique({ where: { id: thandi.id } }))!.passwordHash), /^\$argon2id\$/);
// A sub Accounts doesn't hold for this product keeps the move open.
const stranger = crypto.randomUUID();
const short = await ask({ type: 'import.finish', subs: [thandi.id, sipho.id, stranger] });
assert.equal(short.body.matched, false);
assert.deepEqual(short.body.missing, [stranger]);
assert.ok((await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.importStartedAt);
const finish = await ask({ type: 'import.finish', subs: [thandi.id, sipho.id] });
assert.equal(finish.body.matched, true, JSON.stringify(finish.body));
assert.equal((await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.importStartedAt, null);
});
test('an email that already has an account is linked, not overwritten; a repeat updates', async () => {
const existing = await h.makeAccount({ email: 'already@hope.test', password: 'Accounts-pass-1' });
await begin();
const dup = person({ email: 'ALREADY@hope.test', passwordHash: sealLinkValue(eventsSecret, await bcrypt.hash('Events-pass-99', 4)) });
const again = person({ name: 'Before' });
const first = await ask({ type: 'import.batch', check: false, people: [dup, again] });
const [linked, created] = first.body.results as { outcome: string; sub: string }[];
assert.equal(linked!.outcome, 'linked');
assert.equal(linked!.sub, existing.id);
assert.equal(created!.outcome, 'created');
const still = (await h.db.account.findUnique({ where: { id: existing.id as string } }))!;
assert.equal(still.passwordHash, existing.passwordHash, 'the Accounts password stays');
const repeat = await ask({ type: 'import.batch', check: false, people: [{ ...again, name: 'After' }] });
assert.equal((repeat.body.results as { outcome: string }[])[0]!.outcome, 'updated');
assert.equal((await h.db.account.findUnique({ where: { id: again.id } }))!.name, 'After');
await ask({ type: 'import.abort' });
});
test('a value sealed with another secret, a duplicate email, and a product that isn\'t Events are refused', async () => {
await begin();
const bad = person({ passwordHash: sealLinkValue(newLinkSecret(), '$2b$04$abc') });
assert.equal((await ask({ type: 'import.batch', check: false, people: [bad] })).status, 400);
const twice = person({ email: 'twice@hope.test' });
const res = await ask({ type: 'import.batch', check: false, people: [twice, person({ email: 'twice@hope.test' })] });
assert.deepEqual((res.body.results as { outcome: string }[]).map((r) => r.outcome), ['created', 'refused']);
const website = await ask({ type: 'import.begin', check: false, notices: [], church: { name: null, primaryColour: null } }, { from: PRODUCT_ID, secret: h.linkSecret });
assert.equal(website.body.code, 'WRONG_PRODUCT');
await ask({ type: 'import.abort' });
});
test('Events\' notice versions are taken when Accounts has none, and the church gets its name', async () => {
const fresh = await startHarness();
const secret = newLinkSecret();
await fresh.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: 'https://events.hope.test', publicKey: 'x', secret: fresh.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
await fresh.ctx.settings.set('church_profile', '{}');
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, type: 'import.begin', check: false, church: { name: 'Grace Church', primaryColour: '#123456' }, notices: [{ version: 2, title: 'Our notice', body: 'How we use it.', publishedAt: '2026-02-01T00:00:00.000Z' }] });
const res = await fetch(`${fresh.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret, rawBody: raw }) } });
const body = (await res.json()) as Record<string, unknown>;
assert.equal(body.noticesTaken, true, JSON.stringify(body));
assert.equal((await fresh.db.privacyNotice.findUnique({ where: { version: 2 } }))!.title, 'Our notice');
const profile = await fresh.ctx.settings.json<{ name: string; branding: { colours: { primary: string } } }>('church_profile', {} as never);
assert.equal(profile.name, 'Grace Church');
assert.equal(profile.branding.colours.primary, '#123456');
await fresh.close();
});
});
describe('people.* from a product', () => {
test('people.ensure makes an account and emails a link that sets the password and goes back to the product', async () => {
const res = await ask({ type: 'people.ensure', name: 'New Staff', email: 'new.staff@hope.test', phone: null, returnUrl: 'https://events.hope.test/dashboard' });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(res.body.created, true);
const link = new URL(h.messenger.lastLink('new.staff@hope.test')!);
const browser = new Browser();
const reset = await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'Staff-pass-123' });
assert.equal(reset.body.returnUrl, 'https://events.hope.test/dashboard');
assert.equal((await h.db.account.findUnique({ where: { id: res.body.sub as string } }))!.emailVerified, true);
// The same email again: the same account.
const again = await ask({ type: 'people.ensure', name: 'New Staff', email: 'NEW.staff@hope.test', phone: null, returnUrl: 'https://evil.test/' });
assert.deepEqual([again.body.sub, again.body.created], [res.body.sub, false]);
});
test('a product can only change people it knows', async () => {
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
const res = await ask({ type: 'people.unlock', sub: stranger.id });
assert.equal(res.body.code, 'UNKNOWN_PERSON');
const known = await ask({ type: 'people.ensure', name: 'Known', email: 'known@hope.test', phone: null, returnUrl: 'https://events.hope.test/' });
const sub = known.body.sub as string;
await h.db.account.update({ where: { id: sub }, data: { lockedUntil: new Date(Date.now() + 3600e3), failedSignIns: 9 } });
assert.equal((await ask({ type: 'people.unlock', sub })).body.ok, true);
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.lockedUntil, null);
const taken = await ask({ type: 'people.update', sub, email: 'stranger@hope.test' });
assert.equal(taken.body.code, 'EMAIL_TAKEN');
assert.equal((await ask({ type: 'people.update', sub, name: 'Known Person' })).body.ok, true);
assert.equal((await ask({ type: 'people.newsOff', sub, channel: 'all' })).body.ok, true);
assert.equal((await ask({ type: 'people.setActive', sub, active: false })).body.ok, true);
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/' };
const one = await ask(body, { requestId });
const two = await ask(body, { requestId });
assert.deepEqual(two.body, one.body);
assert.equal(two.body.created, true, 'the first answer, not "already there"');
const forged = await ask(body, { secret: newLinkSecret() });
assert.equal(forged.status, 401);
const unknown = await ask(body, { from: crypto.randomUUID() });
assert.equal(unknown.body.code, 'NOT_LINKED');
});
});
@@ -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');
});
});
@@ -83,13 +83,14 @@ export type Received = { path: string; headers: http.IncomingHttpHeaders; body:
export type Harness = Awaited<ReturnType<typeof startHarness>>;
export async function startHarness(opts: { now?: () => Date } = {}) {
/** `db`: a real Prisma client instead of the in-memory one (an empty, migrated database). */
export async function startHarness(opts: { now?: () => Date; db?: unknown } = {}) {
// Accounts.
const server = http.createServer();
const port = await listen(server);
const publicUrl = `http://127.0.0.1:${port}`;
const config = { ...loadConfig({ ACCOUNTS_URL: publicUrl, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1' }) };
const db = memoryDb();
const db = (opts.db ?? memoryDb()) as MemoryDb;
const messenger = new MemoryMessenger();
const ctx: Ctx = createCtx(config, db as never, { messenger, now: opts.now });
const provider = await createProvider(ctx);
@@ -12,21 +12,21 @@ 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,
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false,
}),
recoveryCode: () => ({ usedAt: null }),
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
emailToken: () => ({ interactionUid: null, usedAt: null }),
emailToken: () => ({ interactionUid: null, returnUrl: null, usedAt: null }),
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 }),
productLink: () => ({ connectedById: null, importStartedAt: 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' };
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' };
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
@@ -148,8 +148,8 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
},
};
const cascade = (from: string, id: unknown) => {
if (from === 'productLink') for (const [k, r] of tables.get('delivery') ?? []) if (r.linkId === id) tables.get('delivery')!.delete(k);
if (from === 'account') for (const t of ['recoveryCode', 'emailToken', 'loginEvent', 'noticeAcceptance', 'consentChange', 'dataExport', 'deletionRequest']) for (const [k, r] of tables.get(t) ?? []) if (r.accountId === id) tables.get(t)!.delete(k);
if (from === 'productLink') for (const t of ['delivery', 'productPerson', 'productRequest']) for (const [k, r] of tables.get(t) ?? []) if (r.linkId === id) tables.get(t)!.delete(k);
if (from === 'account') for (const t of ['recoveryCode', 'emailToken', 'loginEvent', 'noticeAcceptance', 'consentChange', 'dataExport', 'deletionRequest', 'productPerson']) for (const [k, r] of tables.get(t) ?? []) if (r.accountId === id) tables.get(t)!.delete(k);
};
return api;
}
+11 -3
View File
@@ -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,10 @@ test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click();
await page.getByRole("button", { name: "I've saved them" }).click();
await expect(page.getByRole("heading", { name: "Accounts admin" })).toBeVisible();
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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.0.0",
"version": "1.6.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
@@ -1,9 +1,13 @@
"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 { AppShell, PageTitle, ShellLoading } from "@/components/AppShell";
import { Card, Heading } from "@/components/Panel";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -23,37 +27,124 @@ const EVENT: Record<string, string> = {
};
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}&apos;s sites and apps.</p>
<AppShell me={me} active={s.path}>
<PageTitle 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}&apos;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&apos;ve read the latest <a href="/privacy" className="text-brand underline">privacy notice</a></span>}
</div>
</Shell>
</div>
);
}
@@ -64,7 +155,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 +202,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,7 +284,7 @@ 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" });
@@ -249,7 +340,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,5 +1,6 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
@@ -23,7 +24,7 @@ export function ConfirmEmail({ token }: { token: string }) {
<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>
);
+312 -55
View File
@@ -1,63 +1,71 @@
"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 { DatabaseBackup, Download, Play, RefreshCw, Timer } from "lucide-react";
import { Button, Checkbox, Field, Notice } from "@crosscode/ui";
import { 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";
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);
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);
});
return () => { alive = false; };
}, []);
}, [s.path]);
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>;
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 (
<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>
<AppShell me={me} active={s.path}>
<PageTitle sub={s.sub}>{s.title}</PageTitle>
{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>
{section === "people" && <People flash={flash} />}
<div className="max-w-3xl">
{section === "deletions" && <Deletions flash={flash} />}
{section === "church" && <Church flash={flash} />}
{section === "linked" && <Linked flash={flash} />}
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />}
{section === "jobs" && <Jobs flash={flash} />}
{section === "licence" && <Licence flash={flash} />}
{section === "audit" && <Audit />}
</div>
</AppShell>
);
}
@@ -244,6 +252,7 @@ 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"],
@@ -258,7 +267,7 @@ 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>
<form onSubmit={async (e) => {
@@ -283,6 +292,7 @@ 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>
@@ -291,30 +301,48 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
type NoticeVersion = { version: number; title: string; body: string };
function NoticeTab({ flash }: { flash: Flash }) {
const [current, setCurrent] = useState<{ version: number; title: string; body: string } | null>(null);
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: { version: number; title: string; body: string } }>("GET", "/admin/notices");
if (r.ok) setCurrent(r.data.current);
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 (!current) return <p className="text-gray-600">Loading…</p>;
if (!data || !draft) return <p className="text-gray-600">Loading…</p>;
const { current, builtIn } = data;
const isBuiltIn = current.version === 1;
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>
</Card>
<div className="space-y-6">
<Card>
<Heading sub={`Version ${current.version}${isBuiltIn ? " (the built-in notice, filled in from the church profile)" : ""}. Publishing a new version asks everyone to read it the next time they sign in.`}>Edit and publish</Heading>
{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 &quot;## &quot; is a heading, and one starting with &quot;• &quot; is a bullet.</p>
<Button type="submit">Publish a new version</Button>
</form>
</Card>
<Card>
<Heading 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>
);
}
@@ -367,3 +395,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&apos;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&apos;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&apos;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&apos;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&apos;s .env applies: a job&apos;s own flag (e.g. BACKUP_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;. The nightly backup also follows Backups → &quot;Back up every night&quot;.</p>
</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/deletions, /church, /linked, … (/admin itself is People). */
export default async function AdminSectionPage({ params }: { params: Promise<{ section: string }> }) {
const { section } = await params;
if (section === "people" || !(section in ADMIN_SECTIONS)) notFound();
return <Admin section={section as AdminSection} />;
}
@@ -1,5 +1,6 @@
"use client";
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
@@ -13,7 +14,7 @@ export function Forgot({ uid }: { uid: string | null }) {
return (
<Shell branding={branding}>
<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&apos;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>
) : (
+12
View File
@@ -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

+20 -10
View File
@@ -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&apos;t be loaded. Please try again.</p>}
</Card>
</div>
</AppShell>
);
}
@@ -1,5 +1,6 @@
"use client";
import { KeyRound } from "lucide-react";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
@@ -12,16 +13,17 @@ export function Reset({ token }: { token: string | null }) {
return (
<Shell branding={branding}>
<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();
setBusy(true);
const r = await call<{ uid: string | null }>("POST", "/password/reset", { token, password: new FormData(e.currentTarget).get("password") });
const r = await call<{ uid: string | null; returnUrl: string | null }>("POST", "/password/reset", { token, password: new FormData(e.currentTarget).get("password") });
setBusy(false);
if (!r.ok) return setError(r.error.message);
// Back to the sign-in it started from (and on to that site), or to the account page.
window.location.assign(r.data.uid ? `/signin?uid=${encodeURIComponent(r.data.uid)}` : selfSignIn("/account"));
// Back to the sign-in it started from (and on to that site), to the product that made the
// account (its sign-in brings them straight back here signed in), or to the account page.
window.location.assign(r.data.uid ? `/signin?uid=${encodeURIComponent(r.data.uid)}` : r.data.returnUrl ?? selfSignIn("/account"));
}}>
<Field label="New password" name="password" type="password" autoComplete="new-password" required minLength={8} autoFocus />
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
@@ -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,5 +1,6 @@
"use client";
import { LogOut } from "lucide-react";
import { Card, Heading, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { selfSignIn } from "@/lib/api";
@@ -9,7 +10,7 @@ export default function SignedOutPage() {
return (
<Shell branding={branding}>
<Card>
<Heading sub={`You've been signed out of all of ${branding.name}'s sites.`}>You&apos;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&apos;re signed out</Heading>
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
</Card>
</Shell>
@@ -1,9 +1,11 @@
"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 { useBranding } from "@/components/BrandingProvider";
import { NoticeText } from "@/components/NoticeText";
import { call, type ApiError } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
@@ -13,6 +15,7 @@ type State = {
product: string;
signupEnabled: boolean;
loginHint?: string | null;
screen?: "signin" | "signup";
name?: string;
email?: string;
sentTo?: string;
@@ -35,16 +38,29 @@ export function SignIn({ uid }: { uid: string }) {
const [error, setError] = useState<ApiError | null>(null);
const [busy, setBusy] = useState(false);
const [mode, setMode] = useState<"signin" | "signup">("signin");
const [codes, setCodes] = useState<{ codes: string[]; next: string } | null>(null);
const [codes, setCodes] = useState<{ codes: string[]; next: State } | null>(null);
const [opened, setOpened] = useState(false);
const apply = (s: State) => {
// New recovery codes (2FA just set up, or moved in from Cross Events without them) are shown
// first, whatever comes next.
const go = (s: State) => {
if (s.stage === "done" && s.redirectTo) {
if (s.recoveryCodes?.length) setCodes({ codes: s.recoveryCodes, next: s.redirectTo });
else window.location.assign(s.redirectTo);
window.location.assign(s.redirectTo);
return;
}
setState(s);
};
const apply = (s: State) => {
if (!opened) {
setOpened(true);
if (s.screen === "signup" && s.signupEnabled) setMode("signup");
}
if (s.recoveryCodes?.length) {
setCodes({ codes: s.recoveryCodes, next: s });
return;
}
go(s);
};
useExternalEffect(() => {
let alive = true;
@@ -69,12 +85,12 @@ export function SignIn({ uid }: { uid: string }) {
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
if (codes) {
return frame(<RecoveryCodes codes={codes.codes} onDone={() => window.location.assign(codes.next)} />);
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
}
if (!state) {
return frame(error ? (
<>
<Heading>We couldn&apos;t continue</Heading>
<Heading icon={<AlertTriangle className="h-5 w-5" />}>We couldn&apos;t continue</Heading>
<Notice tone="error">{error.message}</Notice>
</>
) : <p className="text-gray-600">Loading…</p>);
@@ -107,7 +123,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 />
@@ -130,7 +146,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")} />
@@ -148,7 +164,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>
@@ -198,7 +214,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) => (
@@ -229,7 +245,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>
@@ -243,9 +259,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&apos;ve read it</Button>
</>
);
@@ -255,7 +271,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,179 @@
"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" };
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 },
];
export const ADMIN_NAV: NavItem[] = [
{ href: "/admin", label: "People", icon: Users },
{ href: "/admin/deletions", label: "Deletion requests", icon: UserX },
{ href: "/admin/church", label: "Church profile", icon: Building2 },
{ href: "/admin/linked", label: "Linked products", icon: Link2 },
{ href: "/admin/signin", label: "Sign-in settings", icon: LogIn },
{ href: "/admin/messages", label: "Email and WhatsApp", icon: Mail },
{ href: "/admin/notice", label: "Privacy notice", icon: FileText },
{ href: "/admin/backups", label: "Backups", icon: DatabaseBackup },
{ href: "/admin/jobs", label: "Background jobs", icon: Timer },
{ href: "/admin/licence", label: "Licence", icon: KeyRound },
{ href: "/admin/audit", label: "Audit log", icon: ScrollText },
];
/** 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>;
}
function NavList({ title, items, active, onNavigate }: { title: string; items: NavItem[]; active: string; onNavigate?: () => void }) {
return (
<div className="mb-6">
<p className="mb-2 px-3 text-[11px] font-semibold uppercase tracking-wide text-gray-400">{title}</p>
<nav className="space-y-1" aria-label={title}>
{items.map((l) => {
const Icon = l.icon;
const on = active === l.href;
return (
<Link key={l.href} href={l.href} onClick={onNavigate} aria-current={on ? "page" : undefined}
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${on ? "bg-brand/10 font-medium text-brand-dark" : "text-gray-600 hover:bg-gray-50"}`}>
<Icon className="h-4 w-4 shrink-0" aria-hidden />
{l.label}
</Link>
);
})}
</nav>
</div>
);
}
function SidebarContent({ me, active, onNavigate }: { me: ShellUser; active: string; onNavigate?: () => void }) {
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>
<NavList title="Your account" items={ACCOUNT_NAV} active={active} onNavigate={onNavigate} />
{me.role === "admin" && <NavList title="Admin" items={ADMIN_NAV} active={active} onNavigate={onNavigate} />}
</>
);
}
/**
* 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 = "", children }: { me: ShellUser | null; active?: string; 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} 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} /></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. */
export function PageTitle({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) {
return (
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">{children}</h1>
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
</div>
);
}
/** 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>
);
}
@@ -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,15 @@
/** The admin's sections (1.3.0): one address each, in the sidebar (components/AppShell.tsx). */
export const ADMIN_SECTIONS = {
people: { path: "/admin", title: "People", sub: "Everyone with a church account. Roles in each site (an Events supervisor, for example) are set in that site." },
deletions: { path: "/admin/deletions", title: "Deletion requests", sub: "People who asked to delete their account." },
church: { path: "/admin/church", title: "Church profile", sub: "The church's name, logo, colours and contact details, used by all its sites." },
linked: { path: "/admin/linked", title: "Linked products", sub: "The church's sites and apps that sign people in here." },
signin: { path: "/admin/signin", title: "Sign-in settings", sub: "Who may make an account, two-step sign-in for admins, and how long people stay signed in." },
messages: { path: "/admin/messages", title: "Email and WhatsApp", sub: "How Accounts sends sign-in codes, password links and security notices." },
notice: { path: "/admin/notice", title: "Privacy notice", sub: "What people read before they sign in for the first time, and after it changes." },
backups: { path: "/admin/backups", title: "Backups", sub: "Copies of the Accounts database, kept on this server." },
jobs: { path: "/admin/jobs", title: "Background jobs", sub: "What the server does on a schedule. Switch a job on or off or change when it runs: your choice wins over the server's .env and applies straight away." },
licence: { path: "/admin/licence", title: "Licence", sub: "Accounts' connection to Cross Code." },
audit: { path: "/admin/audit", title: "Audit log", sub: "What admins and the church's sites changed here." },
} as const;
export type AdminSection = keyof typeof ADMIN_SECTIONS;
+1 -1
View File
@@ -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" }] }],
};
+7 -3
View File
@@ -1,10 +1,12 @@
{
"name": "@crosscode/agent",
"version": "1.1.1",
"version": "1.3.1",
"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",
"bin": { "crosscode-agent": "./dist/cli.js" },
"bin": {
"crosscode-agent": "./dist/cli.js"
},
"scripts": {
"build": "tsup",
"typecheck": "tsc -p tsconfig.json --noEmit",
@@ -14,5 +16,7 @@
"@crosscode/contracts": "*",
"zod": "^4.6.7"
},
"engines": { "node": ">=24" }
"engines": {
"node": ">=24"
}
}
+12
View File
@@ -48,6 +48,18 @@ 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 "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":
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, "--out", opts.exportFile];
+1 -1
View File
@@ -12,7 +12,7 @@ import { paths } from "./paths";
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.1.1";
export const AGENT_VERSION = "1.3.1";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+15
View File
@@ -39,6 +39,21 @@ describe("crosscode arguments for each job", () => {
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
});
it("seed-demo: crosscode demo with the profile, and the admin kept when the Hub names one", () => {
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"]);
});
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", () => {
const j = parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
expect(crosscodeArgs(j, { exportFile: "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip" })).toEqual(["export", "hope", "--out", "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip"]);
+181
View File
@@ -5,6 +5,187 @@ 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.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
Accounts 1.1.0 (`— requires accounts 1.1.0` in WHATS-NEW.md) and contracts 1.8.0. Nothing changes
for people until an admin moves sign-in; see MIGRATING-TO-3.md.
### Added
- **Settings → Sign-in** (`/api/v2/settings/sign-in`, `…/check`, `…/move`, `…/undo`): Check (a dry
run in Accounts: who moves, who is linked to an account they already have, who is refused or
skipped), Move and Undo (14 days). The move sends everyone with a real email address to Accounts
(`crosscode.identity-request/1`, batches of 200, password hashes and authenticator secrets sealed
with the link's secret), checks Accounts holds the same people (count and hash of the subs), and
only then switches `auth_mode` to `accounts`. A move that fails switches nothing and can be run
again. The admin who ran it gets the report by email; it's in the audit log.
- **Signing in through Accounts** (`src/accounts/`): `GET /api/auth/signin?returnTo=` (PKCE, the
state carries the page), `GET /api/auth/callback` (finds the user by `accountId`, links a guest or
unlinked user with the same verified email, or makes a new `user`; keeps Events' copy of the
profile, news consent and 2FA method), then `/auth/complete#<one-time code>`, which the page swaps
for Events' own token at `POST /api/auth/handoff` (60 seconds, single use). Staff roles that need
2FA are sent straight back with `acr_values=mfa` when Accounts didn't ask for it. The token carries
`asi` (the sign-in) and `mfa`, which `protect` checks for staff roles; tokens from before the move
keep working under the old rules.
- **Signing out** (`POST /api/auth/signout`) ends Events' sessions and sends the browser to Accounts'
sign-out, which signs out of every product; **back-channel logout** from Accounts
(`/api/auth/backchannel-logout`) ends that person's Events sessions.
- **Accounts' calls** at `/api/accounts/v1/events`: `user.updated` (the local copy), `user.export`
(Events' export as sections), `user.deleted` (anonymise, or `deferred` while there's a registration
for an event that hasn't ended).
- **Admin, through Accounts:** `/api/v2/users/:id/account/reset-two-factor`, `…/unlock`, `…/active`;
changing someone's name, email or phone (`PATCH /users/:id`) changes their account first. People
staff add (ticket transfers, registrations at the door) get their account from Accounts
(`people.ensure`, a "choose your password" email) instead of an Events activation link.
- `GET /api/v2/auth/mode` (public): `local` or `accounts`, and the church account page.
- `User.accountId` (decision 1), `AccountsSignIn`, six audit actions; the `accounts-secrets` job
clears Events' passwords, authenticator secrets, recovery codes and trusted devices 14 days after
the move, and sign-in records after 40 days.
- `npm run test:accounts` (backend): Events' sign-in and move against the real Accounts app.
- **Connects to the church's Accounts by itself** once the Hub lists it (once: a later Disconnect
stays), so a new install from Hub 2.5.0 needs no Connect.
- **Demo data** with sign-in through Accounts: the demo people get church accounts with the demo
password (`moveNewPeople`, also for anyone added here later without signing in through Accounts).
- `e2e/sign-in-accounts.spec.ts`: the move on Settings → Sign-in and signing in at Accounts' real
pages from a deep link, with Accounts in memory.
### Changed
- With sign-in through Accounts: `/login`, `/register` and `/forgot-password` forward there (every
`/login?redirect=` link keeps working); old reset and activation links say sign-in has moved; Events'
own sign-in, password, 2FA and close-account endpoints answer `409 SIGN_IN_MOVED`; Profile shows the
details read-only and links to the church account for password, 2FA and closing the account; the
privacy centre links there for news, "download my data" and deletion. An unsubscribe link or a
WhatsApp STOP turns news off in Accounts too (`people.newsOff`).
- `useRequireAuth` sends people to `/login?redirect=<this page>`, so they come back to it.
- The inactive-account retention rule skips people linked to Accounts (Accounts keeps or removes
them).
## [2.4.1] - 2026-11-19
### Fixed
- **Demo data on a server** (`scripts/set-demo.js`): run as anyone but the site's user, `.env`
(mode 600) couldn't be read, so `DATABASE_URL` was missing and pg failed with "client password
must be a string", then hung. It now stops at once and says to run it as the site's user (or
`crosscode demo`, which the Hub uses).
- **The default logo** (before a church uploads its own) was still Hope Family Church's artwork; it's
now the Cross Code logo (`frontend/src/app/default_logo.png`).
- The admin account kept can be named with `--admin-email=` (or `DEMO_ADMIN_EMAIL`, as before).
When none is named and joshua@crosscode.co.za isn't on the site, the oldest admin is kept, so a
site installed from the Hub (with the church's own admin) can be seeded.
## [2.4.0] - 2026-11-18
Protocol v2, Linked products, the event feed and `packages/seo` (ROADMAP-v3 phase 2,
+64
View File
@@ -0,0 +1,64 @@
# Moving to Cross Events 3.0
Cross Events 3.0 can sign people in with the **church's account** (Accounts), the one they'll use
for the church website and app too. It's a major version because it needs Accounts 1.1.0 or later
next to it. **Updating to 3.0 changes nothing for anyone**: people keep signing in with their Cross
Events password until an admin moves sign-in (step 4). The plan behind it is
[docs/EVENTS-3.0-PLAN.md](../../docs/EVENTS-3.0-PLAN.md).
## For whoever runs the server
1. **Accounts first.** The church needs Accounts 1.1.0 or later on the same server: in the Hub,
New install → Accounts for this church (an `add-product` job), or update its Accounts. The Hub
won't offer the Events 3.0 update before that (`requires accounts 1.1.0`), and `crosscode deploy`
refuses it too.
2. **Connect them.** In Cross Events, Site settings → Linked products → Accounts → **Connect**. This
also registers Events as a sign-in client of Accounts; nothing else is typed in.
3. **Update Events to 3.0** as usual (scheduled update from the Hub). There's one migration
(`User.accountId`, `AccountsSignIn`, six audit actions) and no new `.env` variable.
4. **Move sign-in** when the church is ready (below).
## For the church's admin: moving sign-in
Site settings → **Sign-in**:
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.
3. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
sign-in). By default every admin is ticked.
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:
- "Sign in" opens the church's sign-in page (with the church's name and colours) and comes back to
the page they were on.
- **Same password, same authenticator app.** People with two-step sign-in get 10 new recovery codes
after their first sign-in (the old ones can't move); they should save them.
- Supervisors and admins still need two-step sign-in; Accounts asks them to set it up if they don't
have it.
- Password, two-step sign-in, news choices, "download my data" and deleting an account are on the
church account (Profile and Privacy link there).
**Undo** (same page) goes back to Cross Events' own sign-in for 14 days. People then sign in with
the password they had at the move; anything changed in Accounts since (a new password, two-step
sign-in set up) doesn't come back. After 14 days Cross Events removes the old passwords and Undo
goes away.
## For integrations
- `POST /api/v2/auth/login`, `…/login/code`, `…/signup`, `…/password/forgot`, `…/password/reset`,
`…/activate`, `/me/two-factor/*`, `/me/verify-password` and `/me/close` answer **`409`** with
`{ "error": { "code": "SIGN_IN_MOVED", "signInUrl": "/api/auth/signin" } }` once sign-in has moved.
A script that signed in with a password needs another way in (ask Cross Code).
- `GET /api/v2/auth/mode` says `local` or `accounts`.
- Tokens are the same as before (`Authorization: Bearer …`, 30 days, ended by signing out). A token
from a sign-in through Accounts also carries `asi` and `mfa`.
- `PATCH /api/v2/me` ignores `name`, `email` and `phone` (they're changed in Accounts) and refuses a
password.
+1 -1
View File
@@ -26,7 +26,7 @@ in-process settings cache TTL) without a server restart.
| `primary_color` | Legacy `accent_color` value if present, else `#4F46E5` (indigo) on the website / `#1e3a5f` (navy) in emails | See [Two different fallbacks](#two-different-fallbacks-for-primary_color) below — this is the one setting with a genuine inconsistency worth knowing about. Drives buttons, links, nav highlights, and the email header/CTA. The Branding tab warns when it is under 4.5:1 against white (too light for white text and links) and offers a darker shade (1.50.0). |
| `secondary_color` | `210 40% 96.1%` background / near-black text (light gray "wash", shadcn's stock theme) | The Branding tab's color picker *pre-fills* `#8B5CF6` as a suggested starting point, but that's only a UI default — if you never hit Save, the actual site uses the light-gray fallback, not violet. |
| `accent_color` | `210 40% 96.1%` background / near-black text (same light gray as Secondary) | Same story as Secondary — the picker pre-fills `#EC4899` (pink) as a suggestion only. |
| `logo_url` | Bundled logo (`frontend/src/app/church_logo.jpg`) | Shown in the navbar. This is still the original Hope Family Church artwork checked into the repo — swap the file (or upload a real logo via the Branding tab) before deploying for a different organisation. |
| `logo_url` | Bundled Cross Code logo (`frontend/src/app/default_logo.png`) | Shown in the navbar until the church uploads its own (Site settings → Branding, or `/setup`). |
| `favicon_url` | `frontend/public/favicon.ico` (the site's original generic favicon) | Shown in the browser tab. |
### Two different fallbacks for `primary_color`
+64
View File
@@ -12,6 +12,70 @@ 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.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
their church account, the same one they'll use for the church website and app. Nothing changes
until an admin chooses **Move sign-in to Accounts** under Site settings → Sign-in.
- **Nobody has to reset anything.** Everyone keeps their password and their authenticator app.
People who use two-step sign-in get new recovery codes the first time they sign in.
- After signing in, people come back to exactly the page they were on, such as an event's
registration form.
- Passwords, two-step sign-in, news choices, "download my data" and deleting an account are on the
church account from then on, for all the church's sites at once.
- Admins can still reset someone's two-step sign-in or unlock them from the People page.
- Changed your mind? **Undo** goes back to Cross Events' own sign-in for 14 days after the move.
## 2.4.1
- Until you upload your own logo (Site settings → Branding), the site now shows the Cross Code
logo.
- A fix for setting up demonstration sites.
## 2.4.0
- **Ready for the Church Website and App.** When your church has them, your events can show on
+1 -1
View File
@@ -84,7 +84,7 @@ Create `backend/.env` from `.env.example`. The only variables you must set are:
| `APP_BASE_URL` | — | Public frontend URL — used in email links (fallback if not set via admin panel) |
| `BACKEND_URL` | — | Public backend URL — used to serve ticket PDFs over WhatsApp |
| `PORT` | — | Port to listen on (default `3000`) |
| `TRUST_PROXY` | — | Set when running behind a reverse proxy (e.g. nginx on a separate server), so `req.ip`/`X-Forwarded-For` are read correctly by rate limiting. Accepts a hop count (`1`), `true`/`false`, or comma-separated trusted proxy IP(s)/CIDR(s). |
| `TRUST_PROXY` | — | Set when running behind a reverse proxy (e.g. nginx on a separate server), so `req.ip`/`X-Forwarded-For` are read correctly by rate limiting. Accepts a hop count (`1`), `true`/`false` (lowercase), `loopback` (behind frp), or comma-separated trusted proxy IP(s)/CIDR(s). Anything else (e.g. `TRUE`) stops the backend starting; the Hub and the crosscode script refuse it. |
| `NODE_ENV` | — | `production` or `development` |
| `WAWP_ACCESS_TOKEN` | — | WAWP fallback token (preferred: set via Admin → Site Settings) |
| `WAWP_INSTANCE_ID` | — | WAWP fallback instance ID (preferred: set via Admin → Site Settings) |
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "2.4.0",
"version": "3.6.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
@@ -18,10 +18,12 @@
"build": "tsc -p tsconfig.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
"typecheck": "tsc -p tsconfig.json --noEmit",
"openapi": "tsx scripts/openapi.ts",
"ai:eval": "tsx scripts/ai-eval.ts"
"ai:eval": "tsx scripts/ai-eval.ts",
"test:accounts": "node --import tsx --test --test-reporter=spec tests/accounts-integration/*.int.mts"
},
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
"@crosscode/auth-client": "*",
"@crosscode/contracts": "*",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
@@ -0,0 +1,41 @@
-- 3.0.0: signing in through the church's Accounts (docs/EVENTS-3.0-PLAN.md).
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_started';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_finished';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_failed';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_undone';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_secrets_cleared';
ALTER TYPE "AdminAuditAction" ADD VALUE 'account_changed_in_accounts';
-- AlterTable
ALTER TABLE "User" ADD COLUMN "accountId" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "User_accountId_key" ON "User"("accountId");
-- CreateTable
CREATE TABLE "AccountsSignIn" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"codeHash" TEXT,
"codeExpires" TIMESTAMP(3),
"codeUsedAt" TIMESTAMP(3),
"returnTo" TEXT NOT NULL,
"idToken" TEXT,
"sid" TEXT,
"mfa" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AccountsSignIn_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "AccountsSignIn_codeHash_key" ON "AccountsSignIn"("codeHash");
-- CreateIndex
CREATE INDEX "AccountsSignIn_userId_idx" ON "AccountsSignIn"("userId");
-- CreateIndex
CREATE INDEX "AccountsSignIn_createdAt_idx" ON "AccountsSignIn"("createdAt");
-- AddForeignKey
ALTER TABLE "AccountsSignIn" ADD CONSTRAINT "AccountsSignIn_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+244 -213
View File
@@ -66,6 +66,10 @@ enum TwoFactorMethod {
model User {
id String @id @default(uuid())
// 3.0.0: the church's account (Accounts' `sub`) this user signs in with. Equal to `id` for
// everyone moved in (docs/EVENTS-3.0-PLAN.md §2); another sub when their email already had an
// account; null for guests, deleted people, and everyone before the move.
accountId String? @unique
name String
email String @unique
password String
@@ -108,76 +112,77 @@ model User {
Event Event[]
FormDraft FormDraft[]
eventsClosed Event[] @relation("EventClosedBy")
eventsReopened Event[] @relation("EventReopenedBy")
eventsClosed Event[] @relation("EventClosedBy")
eventsReopened Event[] @relation("EventReopenedBy")
cashupsPerformed EventCashup[]
pendingResolved EventCashupPendingResolution[] @relation("PendingResolutionBy")
notifyForEvents Event[] @relation("EventNotifyRecipients")
notifyForEvents Event[] @relation("EventNotifyRecipients")
personCashCountsFor EventCashupPersonCount[] @relation("EventCashupPersonCountFor")
personCashCountsEntered EventCashupPersonCount[] @relation("EventCashupPersonCountEnteredBy")
securityEvents SecurityEvent[]
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
securityEvents SecurityEvent[]
accountsSignIns AccountsSignIn[]
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
couponsCreated Coupon[] @relation("CouponCreatedBy")
couponAccess CouponUser[]
couponRedemptions CouponRedemption[] @relation("CouponRedemptionUser")
couponsApplied CouponRedemption[] @relation("CouponRedemptionAppliedBy")
attendeeProfiles Attendee[]
heldTickets Ticket[] @relation("TicketHolder")
waitlistEntries WaitlistEntry[]
scanLocks ScanLock[] @relation("ScanLockOwner")
transfersTo TicketTransfer[] @relation("TransferRecipient")
transfersBy TicketTransfer[] @relation("TransferActor")
ledGroups AllocationGroup[] @relation("AllocationGroupLeader")
feedbackInvites FeedbackInvite[]
feedbackGiven FeedbackResponse[]
impersonationsDone ImpersonationSession[] @relation("ImpersonationAdmin")
attendeeProfiles Attendee[]
heldTickets Ticket[] @relation("TicketHolder")
waitlistEntries WaitlistEntry[]
scanLocks ScanLock[] @relation("ScanLockOwner")
transfersTo TicketTransfer[] @relation("TransferRecipient")
transfersBy TicketTransfer[] @relation("TransferActor")
ledGroups AllocationGroup[] @relation("AllocationGroupLeader")
feedbackInvites FeedbackInvite[]
feedbackGiven FeedbackResponse[]
impersonationsDone ImpersonationSession[] @relation("ImpersonationAdmin")
transferRequests TicketTransferRequest[] @relation("TransferRequester")
impersonatedIn ImpersonationSession[] @relation("ImpersonationTarget")
scanLocksForced ScanLock[] @relation("ScanLockForcedBy")
syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer")
impersonatedIn ImpersonationSession[] @relation("ImpersonationTarget")
scanLocksForced ScanLock[] @relation("ScanLockForcedBy")
syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer")
twoFactorChallenges TwoFactorChallenge[]
trustedDevices TrustedDevice[]
certificates Certificate[]
certificatesIssued Certificate[] @relation("CertificateIssuedBy")
twoFactorChallenges TwoFactorChallenge[]
trustedDevices TrustedDevice[]
certificates Certificate[]
certificatesIssued Certificate[] @relation("CertificateIssuedBy")
communicationConsents CommunicationConsent[]
dataRequests DataRequest[]
dataRequestsHandled DataRequest[] @relation("DataRequestHandledBy")
noticesPublished PrivacyNotice[]
noticeAcceptances NoticeAcceptance[]
dataAccessLogs DataAccessLog[]
breachesRecorded SecurityBreach[]
dataRequests DataRequest[]
dataRequestsHandled DataRequest[] @relation("DataRequestHandledBy")
noticesPublished PrivacyNotice[]
noticeAcceptances NoticeAcceptance[]
dataAccessLogs DataAccessLog[]
breachesRecorded SecurityBreach[]
// Multi-campus (only used while Site settings → Campuses is on).
homeCampusId String?
homeCampus Campus? @relation("UserHomeCampus", fields: [homeCampusId], references: [id], onDelete: SetNull)
campusSummaries Campus[] @relation("CampusNotifyRecipients")
homeCampusId String?
homeCampus Campus? @relation("UserHomeCampus", fields: [homeCampusId], references: [id], onDelete: SetNull)
campusSummaries Campus[] @relation("CampusNotifyRecipients")
// Campus-scoped staff (1.44.0): a supervisor/staff member limited to these campuses (their
// events plus events for all campuses). Empty = unscoped. Ignored for admins and while
// campuses are off (utils/campusScope.js).
scopedCampuses Campus[] @relation("UserCampusScope")
scopedCampuses Campus[] @relation("UserCampusScope")
// Kids check-in (1.45.0): the family this person is a parent in (at most one).
familyMembership FamilyMember?
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
kidsAlertsRaised KidsAlert[]
kidsRoomDuties KidsRoomDuty[]
familyMembership FamilyMember?
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
kidsAlertsRaised KidsAlert[]
kidsRoomDuties KidsRoomDuty[]
// Volunteer rosters (1.46.0)
volunteerSlots VolunteerSlot[] @relation("VolunteerSlotUser")
volunteersAssigned VolunteerSlot[] @relation("VolunteerSlotAssignedBy")
volunteersCheckedIn VolunteerSlot[] @relation("VolunteerSlotCheckedInBy")
volunteerSlots VolunteerSlot[] @relation("VolunteerSlotUser")
volunteersAssigned VolunteerSlot[] @relation("VolunteerSlotAssignedBy")
volunteersCheckedIn VolunteerSlot[] @relation("VolunteerSlotCheckedInBy")
seriesFollows SeriesFollow[]
seasonPassPurchases SeasonPassPurchase[]
savedFilters SavedFilter[]
aiCalls AiCall[]
swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom")
swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo")
swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom")
swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo")
@@index([homeCampusId])
}
@@ -318,27 +323,27 @@ model Event {
// tickets. Each child gets a free place on `kidsOptionId` (a main-ticket option of this
// event) the first time, so they show on the attendance register; rooms are the groups of
// the allocation set `kidsRoomSetId`. Plain ids (checked in utils/kids.js), not relations.
kidsCheckIn Boolean @default(false)
kidsOptionId String?
kidsRoomSetId String?
kidsPickupCodes KidsPickupCode[]
kidsCheckIns KidsCheckIn[]
kidsAlerts KidsAlert[]
kidsCheckIn Boolean @default(false)
kidsOptionId String?
kidsRoomSetId String?
kidsPickupCodes KidsPickupCode[]
kidsCheckIns KidsCheckIn[]
kidsAlerts KidsAlert[]
// Volunteer rosters (1.46.0): serving roles for the event or one of its sessions. When
// `volunteerOptionId` is set (a main ticket of this event; off by default), each volunteer
// gets a free place on it. `volunteerCheckInToken` is in the check-in QR code volunteers scan
// on the day (made the first time the QR code is shown). Plain id, checked in utils/volunteers.js.
servingRoles ServingRole[]
volunteerOptionId String?
volunteerCheckInToken String? @unique
servingRoles ServingRole[]
volunteerOptionId String?
volunteerCheckInToken String? @unique
// Event series (1.47.1): separate events grouped on one series page (Camp 2025, Camp 2026).
// seriesAnnouncedAt: when followers were emailed that this event is out (once, when it goes live).
seriesId String?
series EventSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
seasonPassItems SeasonPassItem[]
seriesAnnouncedAt DateTime?
seriesId String?
series EventSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
seasonPassItems SeasonPassItem[]
seriesAnnouncedAt DateTime?
@@index([createdById])
@@index([closedById])
@@ -502,47 +507,47 @@ model OptionVariant {
}
model Registration {
id String @id @default(uuid())
userId String
eventId String
status RegistrationStatus @default(pending)
checkoutId String? @unique
id String @id @default(uuid())
userId String
eventId String
status RegistrationStatus @default(pending)
checkoutId String? @unique
// Sum of this registration's discounts: bundle deals plus active coupon discounts,
// kept in step with bundleApplications and couponRedemptions. Stored here so every
// total-due calculation sees it no matter which relations the caller loaded (see
// utils/pricing.js computeRegistrationTotalDue).
discountTotal Float @default(0)
discountTotal Float @default(0)
// The bundle-deal part of discountTotal (the rest is coupons).
bundleDiscount Float @default(0)
bundleDiscount Float @default(0)
// Where named attendees' tickets go: all to the payer, or each to the attendee.
ticketDelivery TicketDelivery @default(payer)
ticketDelivery TicketDelivery @default(payer)
// Corrections (1.52.0). The attendee form can come later: tickets don't wait for it ("Fill in
// later" at the door or in Manual registrations, or an admin in Corrections).
formWaivedAt DateTime?
formWaivedById String?
formWaivedAt DateTime?
formWaivedById String?
// An admin issued the tickets before it was paid ("pay later"): the balance is still owed.
ticketsReleasedAt DateTime?
ticketsReleasedById String?
ticketsReleasedAt DateTime?
ticketsReleasedById String?
// A balance an admin wrote off ("make it free"); part of discountTotal (utils/coupons.js).
complimentaryDiscount Float @default(0)
analyticsSessionId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
registrationOptions RegistrationOption[]
payments Payment[]
formResponses FormResponse[]
formDrafts FormDraft[]
couponRedemptions CouponRedemption[]
bundleApplications RegistrationBundle[]
complimentaryDiscount Float @default(0)
analyticsSessionId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
registrationOptions RegistrationOption[]
payments Payment[]
formResponses FormResponse[]
formDrafts FormDraft[]
couponRedemptions CouponRedemption[]
bundleApplications RegistrationBundle[]
// Season pass (1.47.3): one registration per event on the pass, its line priced at that
// event's share of the pass price (never repriced, no coupons, options not editable).
seasonPassPurchaseId String?
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
attendees Attendee[]
waitlistEntries WaitlistEntry[]
volunteerSlots VolunteerSlot[]
seasonPassPurchaseId String?
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
attendees Attendee[]
waitlistEntries WaitlistEntry[]
volunteerSlots VolunteerSlot[]
@@index([userId])
@@index([eventId])
@@ -603,37 +608,37 @@ model RegistrationOptionTranche {
}
model Payment {
id String @id @default(uuid())
amount Float
method String
userId String
recordedById String?
registrationId String?
eventId String?
isDonation Boolean @default(false)
id String @id @default(uuid())
amount Float
method String
userId String
recordedById String?
registrationId String?
eventId String?
isDonation Boolean @default(false)
// A "sponsor a spot" donation (also isDonation): goes into the event's sponsorship pool.
isSponsorship Boolean @default(false)
sponsorName String?
sponsorMessage String?
sponsorAnonymous Boolean @default(false)
externalId String? @unique
status String?
originalPaymentId String?
isSponsorship Boolean @default(false)
sponsorName String?
sponsorMessage String?
sponsorAnonymous Boolean @default(false)
externalId String? @unique
status String?
originalPaymentId String?
// Online payments: the payment provider that took it (src/payments, e.g. "yoco"). Null for
// payments recorded by staff. Payment.method stays the wallet type (card, apple_pay, …).
provider String?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
recordedBy User? @relation("PaymentRecordedBy", fields: [recordedById], references: [id], onDelete: SetNull)
registration Registration? @relation(fields: [registrationId], references: [id], onDelete: SetNull)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
originalPayment Payment? @relation("SplitPayments", fields: [originalPaymentId], references: [id], onDelete: SetNull)
splitPayments Payment[] @relation("SplitPayments")
provider String?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
recordedBy User? @relation("PaymentRecordedBy", fields: [recordedById], references: [id], onDelete: SetNull)
registration Registration? @relation(fields: [registrationId], references: [id], onDelete: SetNull)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
originalPayment Payment? @relation("SplitPayments", fields: [originalPaymentId], references: [id], onDelete: SetNull)
splitPayments Payment[] @relation("SplitPayments")
providerTransactions ProviderTransaction[]
// Season pass: one provider payment is recorded as one Payment per event on the pass (its
// share), all linked to the purchase. Only the first carries the provider's externalId.
seasonPassPurchaseId String?
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
@@index([userId])
@@index([recordedById])
@@ -644,25 +649,25 @@ model Payment {
}
model Ticket {
id String @id @default(uuid())
qrCode String @unique
id String @id @default(uuid())
qrCode String @unique
registrationOptionId String
userId String
eventId String
quantity Int @default(1)
isUsed Boolean @default(false)
emailSent Boolean @default(false)
quantity Int @default(1)
isUsed Boolean @default(false)
emailSent Boolean @default(false)
// Set on a named (group) ticket: the person it's for, and their account when it
// matched one. userId stays the payer.
attendeeId String? @unique
attendee Attendee? @relation(fields: [attendeeId], references: [id], onDelete: SetNull)
attendeeId String? @unique
attendee Attendee? @relation(fields: [attendeeId], references: [id], onDelete: SetNull)
holderUserId String?
holder User? @relation("TicketHolder", fields: [holderUserId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registrationOption RegistrationOption @relation(fields: [registrationOptionId], references: [id], onDelete: Restrict)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
holder User? @relation("TicketHolder", fields: [holderUserId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registrationOption RegistrationOption @relation(fields: [registrationOptionId], references: [id], onDelete: Restrict)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
usages TicketUsage[]
transfers TicketTransfer[]
transferRequests TicketTransferRequest[]
@@ -676,25 +681,25 @@ model Ticket {
}
model TicketUsage {
id String @id @default(uuid())
id String @id @default(uuid())
ticketId String
scannedById String
scannedAt DateTime @default(now())
quantityRedeemed Int @default(1)
scannedAt DateTime @default(now())
quantityRedeemed Int @default(1)
// Offline scanning: the device's id for the scan (makes syncing idempotent), and
// the offline lock it was made under.
clientScanId String? @unique
offline Boolean @default(false)
clientScanId String? @unique
offline Boolean @default(false)
scanLockId String?
syncedAt DateTime?
// Multi-day events: the session this check-in counts for (null on single-date events).
sessionId String?
session EventSession? @relation(fields: [sessionId], references: [id], onDelete: Restrict)
// Ticked present by a supervisor from the attendance register, not scanned.
manual Boolean @default(false)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict)
scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict)
scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull)
manual Boolean @default(false)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict)
scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict)
scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull)
@@index([ticketId])
@@index([scannedAt])
@@ -718,19 +723,19 @@ model PasswordReset {
// ('login') or to prove the channel works before 2FA is switched on ('enable').
// Only the HMAC of the code is stored (see backend/src/utils/twoFactor.js).
model TwoFactorChallenge {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
purpose String // 'login' | 'enable'
method TwoFactorMethod
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
purpose String // 'login' | 'enable'
method TwoFactorMethod
// 2.3.0: an authenticator app being set up: its secret (encrypted) until the first code confirms it.
pendingSecret String?
codeHash String
attempts Int @default(0)
lastSentAt DateTime @default(now())
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
codeHash String
attempts Int @default(0)
lastSentAt DateTime @default(now())
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
@@index([userId])
}
@@ -851,6 +856,12 @@ enum AdminAuditAction {
product_link_disconnected
feed_publish_toggled
feed_show_toggled
sign_in_move_started
sign_in_move_finished
sign_in_move_failed
sign_in_move_undone
sign_in_secrets_cleared
account_changed_in_accounts
}
// Append-only audit trail for admin/supervisor-initiated actions with money or
@@ -970,7 +981,7 @@ model FormDraft {
model ProviderTransaction {
id String @id @default(uuid())
provider String @default("yoco") // payment provider id (src/payments)
externalId String // the provider's payment/event id
externalId String // the provider's payment/event id
amount Int?
currency String?
createdDate DateTime?
@@ -995,19 +1006,19 @@ model ProviderTransaction {
// can be checked against it. Its id is the payer's link (/pay/<id>) and, for PayFast, the
// m_payment_id. `provider` is null until the payer picks one (when several are enabled).
model ProviderCheckout {
id String @id @default(uuid())
id String @id @default(uuid())
provider String?
// The provider's own checkout id (Yoco) and where it sends the payer.
externalId String?
redirectUrl String?
amountCents Int
currency String @default("ZAR")
currency String @default("ZAR")
// Who/what the payment is for: registrationId, userId, eventId, type, donationAmount, …
metadata Json
// Everything needed to start the checkout with any provider: lineItems, return URLs, payer.
request Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([provider, externalId])
}
@@ -1461,16 +1472,16 @@ model FeedbackField {
/// Who was asked. tokenHash is the HMAC of the link token (the token itself isn't stored).
model FeedbackInvite {
id String @id @default(uuid())
formId String
userId String
tokenHash String @unique
sentAt DateTime @default(now())
remindedAt DateTime? // the last reminder (automatic or by hand)
reminderCount Int @default(0)
respondedAt DateTime?
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
id String @id @default(uuid())
formId String
userId String
tokenHash String @unique
sentAt DateTime @default(now())
remindedAt DateTime? // the last reminder (automatic or by hand)
reminderCount Int @default(0)
respondedAt DateTime?
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([formId, userId])
@@index([userId])
@@ -1603,7 +1614,7 @@ model TicketTransfer {
}
model Attendee {
id String @id @default(uuid())
id String @id @default(uuid())
registrationId String
registrationOptionId String?
eventOptionId String
@@ -1617,12 +1628,12 @@ model Attendee {
parentName String?
parentEmail String?
parentPhone String?
order Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registration Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
registrationOption RegistrationOption? @relation(fields: [registrationOptionId], references: [id], onDelete: SetNull)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
order Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registration Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
registrationOption RegistrationOption? @relation(fields: [registrationOptionId], references: [id], onDelete: SetNull)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
ticket Ticket?
formResponses FormResponse[]
consentRequests ConsentRequest[]
@@ -1795,23 +1806,23 @@ enum CheckInWindow {
// One date/time of a multi-day event.
model EventSession {
id String @id @default(uuid())
eventId String
label String?
startsAt DateTime
endsAt DateTime
location String?
id String @id @default(uuid())
eventId String
label String?
startsAt DateTime
endsAt DateTime
location String?
// Cancelled sessions are kept (they may have check-ins) but hidden from the schedule
// and left out of attendance totals.
cancelledAt DateTime?
order Int @default(0)
cancelledAt DateTime?
order Int @default(0)
// Optional limit on people at this session (picked places + whole-course tickets).
capacity Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
usages TicketUsage[]
reminders SessionReminderLog[]
capacity Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
usages TicketUsage[]
reminders SessionReminderLog[]
registrationOptions RegistrationOption[]
waitlistEntries WaitlistEntry[]
servingRoles ServingRole[]
@@ -1834,24 +1845,24 @@ model SessionReminderLog {
// A completion certificate for one ticket (one person).
model Certificate {
id String @id @default(uuid())
eventId String
ticketId String
userId String?
name String
id String @id @default(uuid())
eventId String
ticketId String
userId String?
name String
// Short code printed on the certificate and checked on the public verify page.
code String @unique
sessionsAttended Int @default(0)
totalSessions Int @default(0)
manual Boolean @default(false)
issuedById String?
issuedAt DateTime @default(now())
emailedAt DateTime?
revokedAt DateTime?
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
issuedBy User? @relation("CertificateIssuedBy", fields: [issuedById], references: [id], onDelete: SetNull)
code String @unique
sessionsAttended Int @default(0)
totalSessions Int @default(0)
manual Boolean @default(false)
issuedById String?
issuedAt DateTime @default(now())
emailedAt DateTime?
revokedAt DateTime?
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
issuedBy User? @relation("CertificateIssuedBy", fields: [issuedById], references: [id], onDelete: SetNull)
@@unique([eventId, ticketId])
@@index([userId])
@@ -2187,16 +2198,16 @@ model KidsAlert {
// A leader on duty in a kids room for an occasion ("I'm on duty"), for the ratio.
model KidsRoomDuty {
id String @id @default(uuid())
roomId String
occasion String
userId String
startedAt DateTime @default(now())
endedAt DateTime?
id String @id @default(uuid())
roomId String
occasion String
userId String
startedAt DateTime @default(now())
endedAt DateTime?
// Volunteer rosters (1.46.0): started by a rostered volunteer checking in, not "I'm on duty".
fromRoster Boolean @default(false)
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
fromRoster Boolean @default(false)
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([roomId, occasion])
@@index([userId])
@@ -2288,21 +2299,21 @@ model VolunteerSwap {
/// Outbound webhooks (1.48.0): a URL that is sent what happens here (registrations, payments,
/// check-ins, new accounts, published events), signed with its own secret.
model WebhookEndpoint {
id String @id @default(uuid())
name String
url String
id String @id @default(uuid())
name String
url String
// HMAC secret, encrypted (utils/encryption.js); shown to the admin once, when made or rotated.
secret String
secret String
// Event types it gets, e.g. ["registration.paid", "ticket.checked_in"].
events String[]
isActive Boolean @default(true)
events String[]
isActive Boolean @default(true)
// The operator register entry made for it (POPIA), if any.
operatorId String?
operatorId String?
lastSuccessAt DateTime?
lastFailureAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries WebhookDelivery[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries WebhookDelivery[]
}
/// One message to one endpoint, with its retries. Kept 30 days.
@@ -2442,3 +2453,23 @@ model ImportedEvent {
@@index([linkId])
@@index([endsAt])
}
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §3): one sign-in through the church's Accounts. The callback
// makes it with a one-time handoff code (hashed, 60 seconds) that the page swaps for Events' own
// token; the token carries this row's id (`asi`), so signing out can send Accounts the ID token.
model AccountsSignIn {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
codeHash String? @unique
codeExpires DateTime?
codeUsedAt DateTime?
returnTo String
idToken String? // encrypted (utils/encryption)
sid String?
mfa Boolean @default(false)
createdAt DateTime @default(now())
@@index([userId])
@@index([createdAt])
}
+73 -7
View File
@@ -16,8 +16,9 @@
* campus-limited staff, a series across campuses, kids check-in and rosters at two
* campuses.
*
* Everything is removed first EXCEPT the site settings (AppSetting) and the admin
* account (DEMO_ADMIN_EMAIL, default joshua@crosscode.co.za). Dates are relative to
* 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
* today, so the upcoming events are always in the future whenever this is run.
*
* No emails or WhatsApp messages are sent. Demo people use @example.com addresses and
@@ -40,7 +41,18 @@ const fs = require('fs');
const crypto = require('crypto');
const readline = require('readline');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
const ENV_FILE = path.resolve(__dirname, '../.env');
const loaded = require('dotenv').config({ path: ENV_FILE, quiet: true });
// Without DATABASE_URL the pg driver fails with "client password must be a string" and hangs. The
// usual reason on a server: .env is readable only by the site's own user (mode 600).
if (!process.env.DATABASE_URL && !process.argv.includes('--list')) {
const denied = loaded.error && loaded.error.code === 'EACCES';
console.error(denied
? `Can't read ${ENV_FILE}: it belongs to the site's user. Run this as that user, e.g.\n sudo -u <site user> npm run demo:ministry\nor, as root: crosscode demo <church> --profile ministry`
: `DATABASE_URL isn't set (${loaded.error ? `${ENV_FILE}: ${loaded.error.code || loaded.error.message}` : `not in ${ENV_FILE}`}). Nothing was changed.`);
process.exit(1);
}
const { hashPassword } = require('../src/config/auth');
const { v4: uuidv4 } = require('uuid');
@@ -49,7 +61,11 @@ const { applyBundles } = require('../src/utils/bundles');
const prisma = createPrismaClient();
const ADMIN_EMAIL = (process.env.DEMO_ADMIN_EMAIL || 'joshua@crosscode.co.za').trim().toLowerCase();
// The account kept: --admin-email= or DEMO_ADMIN_EMAIL (must exist), else joshua@crosscode.co.za
// if it's there, else the oldest admin (a site installed from the Hub has its own admin).
const ADMIN_ARG = (process.argv.find(a => a.startsWith('--admin-email=')) || '').slice('--admin-email='.length);
const ADMIN_NAMED = (ADMIN_ARG || process.env.DEMO_ADMIN_EMAIL || '').trim().toLowerCase();
const ADMIN_EMAIL = ADMIN_NAMED || 'joshua@crosscode.co.za';
const DEMO_PASSWORD = 'Demo@1234';
const SKIP_PROMPT = process.argv.includes('--yes') || process.argv.includes('-y');
const PROFILE_NAME = (process.argv.find(a => a.startsWith('--profile=')) || '--profile=events').split('=')[1].trim().toLowerCase();
@@ -60,6 +76,9 @@ 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',
]);
const SCHEDULED_EMAILS_PATH = path.resolve(__dirname, '../data/scheduled-emails.json');
@@ -1846,9 +1865,13 @@ async function main() {
return;
}
admin = await prisma.user.findFirst({ where: { email: { equals: ADMIN_EMAIL, mode: 'insensitive' } } });
if (!admin && !ADMIN_NAMED) {
admin = await prisma.user.findFirst({ where: { role: 'admin' }, orderBy: { createdAt: 'asc' } });
if (admin) console.log(`Keeping the site's first admin, ${admin.email} (${ADMIN_EMAIL} isn't here).`);
}
if (!admin) {
console.error(`Admin account ${ADMIN_EMAIL} was not found — nothing was changed.`);
console.error('Set DEMO_ADMIN_EMAIL to the account you want to keep.');
console.error(`Admin account ${ADMIN_NAMED || 'to keep'} was not found — nothing was changed.`);
console.error('Name the account to keep with --admin-email= or DEMO_ADMIN_EMAIL (or finish /setup first).');
process.exitCode = 1;
return;
}
@@ -1868,6 +1891,9 @@ 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);
const cleared = await prisma.$transaction(async (tx) => {
const result = await clearData(tx);
for (const model of INSERT_ORDER) {
@@ -1884,6 +1910,7 @@ async function main() {
}, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 });
clearScheduledEmails();
const pastFinancials = await closePastEvents();
const accounts = await demoAccounts(oldSubs);
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
@@ -1932,9 +1959,48 @@ async function main() {
console.log(`Demo staff logins (password ${DEMO_PASSWORD}):`);
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('; ')})` : ''}.`);
}
}
/**
* 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). 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(oldSubs = []) {
const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js');
let move;
if (fs.existsSync(dist)) {
move = require(dist);
accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db'));
} else {
require('tsx/cjs');
move = require('../src/accounts/move.ts');
}
const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } });
if (mode?.value !== 'accounts') return null;
try {
// 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;
return null;
}
}
main()
.catch(err => { console.error(err); process.exitCode = 1; })
// The cashup code used by closePastEvents has its own client (src/config/db).
.finally(() => Promise.all([prisma.$disconnect(), require('../src/config/db').$disconnect()]));
.finally(() => Promise.all([prisma.$disconnect(), require('../src/config/db').$disconnect(), accountsDb?.$disconnect()]));
@@ -0,0 +1,29 @@
/**
* Cross Events 3.0 connects itself to the church's Accounts (docs/EVENTS-3.0-PLAN.md §9, Hub
* 2.5.0): after a heartbeat, when the Hub lists an Accounts for this church and this site isn't
* linked to one, it connects (as an admin pressing Connect under Linked products would). Once
* only: after it worked (`accounts_auto_connected`), an admin's Disconnect stays as it is.
*/
import { connectTo } from '../links/connect';
import { linkedProducts } from '../links/store';
import { accountsLink } from './client';
import { getSetting, setSetting, viaAccounts } from './mode';
export const AUTO_KEY = 'accounts_auto_connected';
export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> {
// 3.5.0: a site that signs in through Accounts but has lost its link (before 3.5.0, loading demo
// data deleted it) can't sign anyone in, so it reconnects whatever was done before. A site on its
// own sign-in keeps an admin's Disconnect.
const stranded = (await viaAccounts()) && !(await accountsLink());
if ((await getSetting(AUTO_KEY)) && !stranded) return 'skipped';
if (await accountsLink()) {
await setSetting(AUTO_KEY, now.toISOString());
return 'skipped';
}
const listed = (await linkedProducts()).find((p) => p.product === 'accounts');
if (!listed) return 'skipped';
await connectTo(listed.installId, { id: null, role: 'system' }, null, now);
await setSetting(AUTO_KEY, now.toISOString());
return 'connected';
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Accounts' signed calls to Events (`crosscode.identity/1`, 3.0.0, docs/EVENTS-3.0-PLAN.md §7):
*
* - `user.updated`: keep Events' copy of the profile and news consent current.
* - `user.export`: Events' part of "Download my data", from the same export Events' own privacy
* page gives (utils/privacy.exportUserData), as sections.
* - `user.deleted`: Events' existing rules: anonymise, keeping financial records without the name;
* `deferred` while the person has a registration for an event that hasn't ended.
*
* A call for someone Events doesn't know is answered as done: there's nothing here to change.
*/
import { IDENTITY_SCHEMA, type AccountsCall, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
import { updateLocalCopy, endEventsSessions } from './signin';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const privacy = require('../utils/privacy') as {
exportUserData(userId: string): Promise<Record<string, unknown> | null>;
deletionBlockers(userId: string): Promise<{ eventTitle: string; endDate: Date }[]>;
anonymiseUser(userId: string): Promise<unknown>;
};
/* eslint-enable @typescript-eslint/no-require-imports */
const TITLES: Record<string, string> = {
account: 'Your Cross Events details',
registrations: 'Registrations',
payments: 'Payments',
tickets: 'Tickets and check-ins',
waitlist: 'Waiting lists',
certificates: 'Certificates',
feedback: 'Feedback you gave',
consents: 'Message preferences (history)',
accountActivity: 'Sign-ins to Cross Events before the move',
dataRequests: 'Privacy requests',
notices: 'Privacy notices accepted',
kidsFamily: 'Family and children',
volunteering: 'Volunteering',
seriesFollowed: 'Series you follow',
seasonPasses: 'Season passes',
};
const sectionKey = (k: string) => k.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/[^a-z0-9_]/g, '').replace(/^[^a-z]+/, '').slice(0, 50) || 'other';
const asRecords = (v: unknown): Record<string, unknown>[] =>
(Array.isArray(v) ? v : v && typeof v === 'object' ? [v] : []).map((x) => (x && typeof x === 'object' ? (JSON.parse(JSON.stringify(x)) as Record<string, unknown>) : { value: x }));
/** Events' export as `crosscode.identity/1` sections (at most 100). */
export function exportSections(data: Record<string, unknown>) {
return Object.entries(data)
.filter(([, v]) => v !== null && v !== undefined)
.map(([k, v]) => ({ key: sectionKey(k), title: TITLES[k] ?? k, records: asRecords(v) }))
.filter((s) => s.records.length > 0)
.slice(0, 100);
}
const DEFER_HOURS = 24;
export async function handleAccountsCall(call: AccountsCall): Promise<object> {
const user = await prisma.user.findUnique({ where: { accountId: call.sub }, select: { id: true } });
switch (call.type) {
case 'user.updated': {
if (user) await updateLocalCopy(user.id, call.profile);
return { schema: IDENTITY_SCHEMA, ok: true };
}
case 'user.export': {
const data = user ? await privacy.exportUserData(user.id) : null;
const reply: UserExportReply = {
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'events', generatedAt: new Date().toISOString(),
sections: data ? exportSections(data) : [],
};
return reply;
}
case 'user.deleted': {
if (!user) return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
const blockers = await privacy.deletionBlockers(user.id);
if (blockers.length) {
const first = blockers[0]!;
const end = new Date(Math.max(new Date(first.endDate).getTime(), Date.now()) + DEFER_HOURS * 3600e3);
const more = blockers.length > 1 ? ` and ${blockers.length - 1} more` : '';
return {
schema: IDENTITY_SCHEMA, status: 'deferred',
reason: `Has a registration for ${first.eventTitle} (${new Date(first.endDate).toISOString().slice(0, 10)})${more}`.slice(0, 500),
retryAfter: end.toISOString(),
} satisfies UserDeletedReply;
}
await endEventsSessions(user.id);
await privacy.anonymiseUser(user.id);
await prisma.user.update({ where: { id: user.id }, data: { accountId: null } }).catch(() => {});
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
}
}
}
@@ -0,0 +1,74 @@
/**
* The church's Accounts, as this site's OIDC client (3.0.0, docs/EVENTS-3.0-PLAN.md §1): built on
* `@crosscode/auth-client` from the Accounts link that Connect made (Settings → Linked products).
* Its address is the one the Hub listed; its client id is this site's Hub install id and its client
* secret comes from the link's secret, so there's no `.env` setting for any of it.
*
* `@crosscode/auth-client` and `openid-client` are ES modules and this backend is CommonJS, which
* compiles `import()` into `require()`. The loader below keeps a real dynamic import, so it works on
* every Node the servers run (20+), not only where `require()` of ES modules is allowed.
*/
import type { AccountsClient } from '@crosscode/auth-client';
import { hubInstallId, siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthClientModule = typeof import('@crosscode/auth-client');
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- a real import(), see above
const importEsm = new Function('specifier', 'return import(specifier)') as (s: string) => Promise<AuthClientModule>;
let loader: () => Promise<AuthClientModule> = () => importEsm('@crosscode/auth-client');
/** Tests: use another auth-client (a fake, or the real one loaded another way). */
export function setAuthClientLoader(next: () => Promise<AuthClientModule>): void {
loader = next;
cached = null;
}
export class AccountsUnavailable extends Error {
status = 503;
code = 'ACCOUNTS_UNAVAILABLE';
}
export type AccountsLink = { installId: string; url: string; secret: string; updatedAt: Date };
/** The Accounts link, or null when Accounts isn't connected. */
export async function accountsLink(): Promise<AccountsLink | null> {
return prisma.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
}
let cached: { key: string; client: Promise<AccountsClient> } | null = null;
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
export async function accounts(): Promise<AccountsClient> {
const link = await accountsLink();
if (!link) throw new AccountsUnavailable('Accounts isn\'t connected. Connect it under Settings → Linked products.');
const [clientId, productUrl] = await Promise.all([hubInstallId(), siteUrl()]);
if (!clientId) throw new AccountsUnavailable('This site isn\'t connected to the Hub yet.');
const key = `${link.installId}|${new Date(link.updatedAt).getTime()}|${clientId}|${productUrl}`;
if (!cached || cached.key !== key) {
const client = loader().then((m) => m.accountsClient({
accountsUrl: link.url,
productUrl,
clientId,
linkSecret: decrypt(link.secret),
allowInsecure: process.env.NODE_ENV !== 'production' && link.url.startsWith('http:'),
}));
// A failed discovery (Accounts down for a moment) is tried again next time.
client.catch(() => { if (cached?.key === key) cached = null; });
cached = { key, client };
}
try {
return await cached.client;
} catch (e) {
throw new AccountsUnavailable(`Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
}
}
/** The module itself (for its error classes). */
export function authClientModule(): Promise<AuthClientModule> {
return loader();
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Cross Events' own sign-in, once sign-in goes through Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §6).
* Mounted after express.json, before the API:
*
* - Signing in, signing up, passwords, activation and 2FA here answer 409 `SIGN_IN_MOVED` with
* where to go instead (the frontend forwards there).
* - While a move runs, Events' own sign-in waits (503 `SIGN_IN_MOVING`).
* - Changing my name, email or phone is done in Accounts (`PATCH /me` keeps the rest).
* - An admin changing someone's name, email or phone (`PATCH /users/:id`) changes their account in
* Accounts first (`people.update`), then Events' copy; a password or 2FA change is refused.
*/
import type { NextFunction, Request, Response } from 'express';
import { accounts, AccountsUnavailable } from './client';
import { getSetting, viaAccounts } from './mode';
import { RUNNING_KEY } from './move';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
const MOVED = [
'POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/login/code/resend', 'POST /api/v2/auth/signup',
'POST /api/v2/auth/password/forgot', 'POST /api/v2/auth/password/reset', 'POST /api/v2/auth/activate',
'POST /api/v2/me/verify-password', 'POST /api/v2/me/close',
];
const MOVED_PREFIXES = ['POST /api/v2/me/two-factor/'];
const LOCAL_SIGN_IN = ['POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/signup', 'POST /api/v2/auth/activate'];
const movedAnswer = (res: Response) => res.status(409).json({
error: {
code: 'SIGN_IN_MOVED',
message: 'Signing in, passwords and two-step sign-in are now on your church account. Use "Sign in" to continue.',
signInUrl: '/api/auth/signin',
},
});
export async function signInGuard(req: Request, res: Response, next: NextFunction) {
const key = `${req.method} ${req.path.replace(/\/+$/, '')}`;
const isMoved = MOVED.includes(key) || MOVED_PREFIXES.some((p) => key.startsWith(p));
const isMe = key === 'PATCH /api/v2/me';
const isAdminEdit = /^PATCH \/api\/v2\/users\/[^/]+$/.test(key);
if (!isMoved && !isMe && !isAdminEdit) return next();
try {
if (!(await viaAccounts())) {
if (LOCAL_SIGN_IN.includes(key)) {
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) {
return res.status(503).json({ error: { code: 'SIGN_IN_MOVING', message: 'One moment, we\'re updating the sign-in. Please try again in a minute.' } });
}
}
return next();
}
if (isMoved) return movedAnswer(res);
const body = (req.body ?? {}) as Record<string, unknown>;
if (isMe) {
if (body.password !== undefined || body.currentPassword !== undefined) return movedAnswer(res);
delete body.name;
delete body.email;
delete body.phone;
return next();
}
// An admin's change to someone (the route itself checks they're an admin).
if (body.password !== undefined || body.twoFactorEnabled !== undefined) return movedAnswer(res);
const changes: { name?: string; email?: string; phone?: string | null } = {};
if (typeof body.name === 'string') changes.name = body.name.trim();
if (typeof body.email === 'string') changes.email = body.email.trim().toLowerCase();
if (body.phoneNumber !== undefined) changes.phone = body.phoneNumber ? String(body.phoneNumber) : null;
if (!Object.keys(changes).length) return next();
const target = await prisma.user.findUnique({ where: { id: String(req.params?.id ?? req.path.split('/').pop()) }, select: { id: true, accountId: true, name: true, email: true, phoneNumber: true } });
if (!target?.accountId) return next();
const differs = (changes.name !== undefined && changes.name !== target.name) || (changes.email !== undefined && changes.email !== target.email) || (changes.phone !== undefined && changes.phone !== target.phoneNumber);
if (!differs) return next();
// Only for a signed-in admin: anyone else is refused by the route itself, untouched here.
const admin = await signedInAdmin(req);
if (!admin) return next();
await (await accounts()).request({ type: 'people.update', actor: admin.accountId, sub: target.accountId, ...changes });
return next();
} catch (e) {
if (e instanceof AccountsUnavailable) return res.status(503).json({ error: { code: 'UNAVAILABLE', message: e.message } });
const err = e as { code?: string; message: string };
if (err.code === 'EMAIL_TAKEN') return res.status(409).json({ error: { code: 'CONFLICT', message: 'Another account has that email address.' } });
if (err.code) return res.status(502).json({ error: { code: 'UNAVAILABLE', message: `Accounts didn't accept the change: ${err.message}` } });
return next(e);
}
}
/**
* The request's user when it's a valid, current admin token (as `protect` + `admin` would accept,
* not viewing as someone else), or null. Their `accountId` goes to Accounts' audit log.
*/
async function signedInAdmin(req: Request): Promise<{ id: string; accountId: string | null } | null> {
try {
const header = String(req.headers.authorization || '');
if (!header.startsWith('Bearer ')) return null;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const decoded = jwt.verify(header.slice(7), process.env.JWT_SECRET, { algorithms: ['HS256'] }) as { id?: string; tokenVersion?: number; imp?: string; asi?: string; mfa?: boolean };
// Viewing as someone, or an Accounts sign-in without the second step admins need.
if (!decoded.id || decoded.imp || (decoded.asi && decoded.mfa !== true)) return null;
const u = await prisma.user.findUnique({ where: { id: decoded.id }, select: { id: true, accountId: true, role: true, isActive: true, tokenVersion: true } });
if (!u || !u.isActive || u.role !== 'admin' || (decoded.tokenVersion ?? 0) !== u.tokenVersion) return null;
return { id: u.id, accountId: u.accountId };
} catch {
return null;
}
}
+31
View File
@@ -0,0 +1,31 @@
/**
* This site's look (3.1.0) for the church's Accounts sign-in pages: its name, logo and colours, so
* signing in looks like the church's own site. Sent with a move (filling what Accounts doesn't have
* yet) and by Settings → Sign-in → "Use this site's logo and colours" (replacing it).
*/
import type { ChurchLook } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
/* eslint-enable @typescript-eslint/no-require-imports */
const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null);
export async function churchLook(): Promise<ChurchLook> {
const name = (await getSetting('org_name', '')) || (await getSetting('site_name', '')) || null;
const primary = hex(await getSetting('primary_color', '')) || hex(await getSetting('brand_color', ''));
const accent = hex(await getSetting('accent_color', '')) || hex(await getSetting('secondary_color', ''));
// The logo as an address anyone can load: an uploaded one is a path on this site.
const raw = String(await getSetting('logo_url', '')).trim();
let logoUrl: string | null = null;
if (raw) {
try {
const u = new URL(raw, `${(await siteUrl()).replace(/\/+$/, '')}/`);
if (/^https?:$/.test(u.protocol)) logoUrl = u.toString();
} catch {
logoUrl = null;
}
}
return { name: name ? name.slice(0, 200) : null, primaryColour: primary, accentColour: accent, logoUrl };
}
@@ -0,0 +1,85 @@
/**
* Email and WhatsApp for the church's Accounts (3.1.0). Accounts sends its own sign-in codes and
* password links, with its own settings, which a move doesn't bring along: a church that moved
* sign-in without them couldn't sign in at all. Settings → Sign-in therefore shows what Accounts can
* send, offers this site's own SMTP and WAWP settings to copy (the password and token stay on the
* server: blank means "use this site's"), tests them through Accounts, and saves them there only
* once the test worked (`crosscode.identity-request/1` messaging.*, contracts 1.9.0). The move
* itself needs Accounts' email to work (move.ts).
*/
import type { MessagingStatusReply, MessagingTestReply } from '@crosscode/contracts';
import { accounts } from './client';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
const whatsapp = require('../utils/whatsapp') as { getConfig(): Promise<{ token: string; instanceId: string }> };
/* eslint-enable @typescript-eslint/no-require-imports */
type Smtp = { host: string; port: number; secure: boolean; user: string; pass: string; from: string };
/** This site's SMTP settings, as utils/email.js reads them (the database, then the .env). */
async function eventsSmtp(): Promise<Smtp | null> {
const env = process.env;
const host = await getSetting('smtp_host', env.SMTP_HOST || env.EMAIL_HOST || '');
if (!host) return null;
const port = parseInt(await getSetting('smtp_port', env.SMTP_PORT || env.EMAIL_PORT || '587'), 10) || 587;
return {
host,
port,
secure: String(await getSetting('smtp_secure', env.SMTP_SECURE || env.EMAIL_SECURE || 'false')).toLowerCase() === 'true',
user: await getSetting('smtp_user', env.SMTP_USER || env.EMAIL_USER || ''),
pass: await getSetting('smtp_pass', env.SMTP_PASS || env.EMAIL_PASS || ''),
from: await getSetting('smtp_from', env.MAIL_FROM || env.EMAIL_FROM || ''),
};
}
/** What this site has, to offer for copying: never the password or token themselves. */
export async function eventsMessaging() {
const smtp = await eventsSmtp();
const wa = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
return {
email: smtp ? { host: smtp.host, port: smtp.port, secure: smtp.secure, user: smtp.user, from: smtp.from || smtp.user, hasPass: !!smtp.pass } : null,
whatsapp: wa.instanceId ? { instanceId: wa.instanceId, hasToken: !!wa.token } : null,
};
}
/** What Accounts can send now. */
export async function accountsMessaging(): Promise<Omit<MessagingStatusReply, 'schema'>> {
const r = await (await accounts()).request<MessagingStatusReply>({ type: 'messaging.status', actor: null });
return { email: r.email, whatsapp: r.whatsapp };
}
export type MessagingInput = {
email?: { host: string; port: number; secure: boolean; user: string; from: string; pass?: string | null; to: string };
whatsapp?: { instanceId: string; accessToken?: string | null; to: string };
};
/**
* Tests (and with `save`, saves) settings in Accounts. A blank password or token means this site's
* own; Accounts gets it sealed with the link's secret. Returns Accounts' answer per part.
*/
export async function sendToAccounts(input: MessagingInput, opts: { save: boolean; actor: string | null }): Promise<Omit<MessagingTestReply, 'schema'>> {
const auth = await accounts();
let email;
if (input.email) {
const own = await eventsSmtp();
const pass = input.email.pass ? input.email.pass : (own?.pass ?? '');
email = {
settings: { host: input.email.host.trim(), port: input.email.port, secure: input.email.secure, user: input.email.user.trim(), from: input.email.from.trim(), pass: pass ? auth.seal(pass) : null },
to: input.email.to.trim(),
};
}
let wa;
if (input.whatsapp) {
const own = await whatsapp.getConfig().catch(() => ({ token: '', instanceId: '' }));
const token = input.whatsapp.accessToken ? input.whatsapp.accessToken : own.token;
wa = { settings: { instanceId: input.whatsapp.instanceId.trim(), accessToken: token ? auth.seal(token) : null }, to: input.whatsapp.to.trim() };
}
const r = await auth.request<MessagingTestReply>({
type: opts.save ? 'messaging.set' : 'messaging.test',
actor: opts.actor,
...(email ? { email } : {}),
...(wa ? { whatsapp: wa } : {}),
}, { timeoutMs: 60000 });
return { email: r.email, whatsapp: r.whatsapp, status: r.status };
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Where people sign in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): `local` (Cross Events' own sign-in, as
* 2.x, before the move or after Undo) or `accounts` (through the church's Accounts). Kept in
* AppSetting `auth_mode`; read with a short cache, so every PM2 process follows a move within
* seconds. A new install starts in `accounts` (§9); everyone else starts in `local`.
*
* Other keys: `auth_moved_at` (ISO, when the move finished: Undo is allowed for 14 days, then the
* old secrets are cleared), `auth_move_report` (JSON), `auth_secrets_cleared_at` (ISO).
*/
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthMode = 'local' | 'accounts';
export const MODE_KEY = 'auth_mode';
export const MOVED_AT_KEY = 'auth_moved_at';
export const REPORT_KEY = 'auth_move_report';
export const CLEARED_KEY = 'auth_secrets_cleared_at';
export const UNDO_DAYS = 14;
const TTL_MS = 5000;
let cache: { mode: AuthMode; at: number } | null = null;
export async function authMode(): Promise<AuthMode> {
if (cache && Date.now() - cache.at < TTL_MS) return cache.mode;
const row = await prisma.appSetting.findUnique({ where: { key: MODE_KEY } }).catch(() => null);
const mode: AuthMode = row?.value === 'accounts' ? 'accounts' : 'local';
cache = { mode, at: Date.now() };
return mode;
}
export async function viaAccounts(): Promise<boolean> {
return (await authMode()) === 'accounts';
}
export async function setSetting(key: string, value: string | null): Promise<void> {
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
if (key === MODE_KEY) cache = null;
}
export async function getSetting(key: string): Promise<string | null> {
return (await prisma.appSetting.findUnique({ where: { key } }))?.value ?? null;
}
/** For tests. */
export function forgetMode(): void {
cache = null;
}
+398
View File
@@ -0,0 +1,398 @@
/**
* Moving sign-in to the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §4–§5), from
* Settings → Sign-in:
*
* check() a dry run: who would be moved, linked to an existing account, skipped or refused
* move() copies everyone into Accounts (crosscode.identity-request/1, batches of 200, secrets
* sealed with the link's secret), checks Accounts holds the same people, then switches
* `auth_mode` to `accounts`. Idempotent: a failed move can be run again
* undo() back to Cross Events' own sign-in, for 14 days (the old passwords are still here)
* clearOldSecrets() after those 14 days: Events' password hashes, authenticator secrets,
* recovery codes and trusted devices go (the `accounts-secrets` job)
*
* Who moves: everyone with a real email address who isn't linked yet. Guests (`@guest.local`) and
* deleted people stay Events-only. Recovery codes don't move (decision 2): Accounts shows new ones.
*/
import crypto from 'node:crypto';
import { IMPORT_BATCH_MAX, phoneSchema, REMOVE_DEMO_MAX, type ImportPerson, type ImportResult } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, accountsLink, AccountsUnavailable } from './client';
import { accountsMessaging } from './messaging';
import { churchLook } from './look';
import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
/* eslint-enable @typescript-eslint/no-require-imports */
export class MoveError extends Error {
constructor(message: string, public code = 'MOVE_FAILED', public status = 409) {
super(message);
}
}
/** While a move runs, Cross Events' own sign-in waits (people already signed in stay signed in). */
export const RUNNING_KEY = 'auth_move_running';
const MIN_ACCOUNTS = [1, 1, 0];
const NOT_MOVED = /@(guest\.local|deleted\.invalid|deleted\.local)$/i;
const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/;
const iso = (d: Date | string | null | undefined) => (d ? new Date(d).toISOString() : null);
type Row = {
id: string; name: string; email: string; phoneNumber: string | null; password: string; role: string; isActive: boolean; createdAt: Date;
failedAttempts: number; lockUntil: Date | null; twoFactorEnabled: boolean; twoFactorMethod: string | null; totpSecret: string | null; totpLastStep: number | null;
newsEmail: boolean; newsWhatsApp: boolean; newsAskedAt: Date | null; noticeVersionAccepted: number | null; lastLoginAt: Date | null;
};
const SELECT = {
id: true, name: true, email: true, phoneNumber: true, password: true, role: true, isActive: true, createdAt: true, failedAttempts: true, lockUntil: true,
twoFactorEnabled: true, twoFactorMethod: true, totpSecret: true, totpLastStep: true, newsEmail: true, newsWhatsApp: true, newsAskedAt: true,
noticeVersionAccepted: true, lastLoginAt: true,
} as const;
/** The people who move: a real email, not linked yet. */
async function peopleToMove(): Promise<Row[]> {
const rows: Row[] = await prisma.user.findMany({ where: { accountId: null }, select: SELECT, orderBy: { createdAt: 'asc' } });
return rows.filter((u) => !NOT_MOVED.test(u.email));
}
async function skippedCount(): Promise<number> {
const rows: { email: string }[] = await prisma.user.findMany({ where: { accountId: null }, select: { email: true } });
return rows.filter((u) => NOT_MOVED.test(u.email)).length;
}
/** Accounts' notice versions are Events' + 1: its built-in notice is 1, Events' is 0 (null: never accepted). */
const toAccountsVersion = (v: number | null) => (v === null || v === undefined ? 0 : v + 1);
/** Never activated (made by staff, the link not used yet): Accounts' "choose your password" instead. */
const pendingActivation = (u: Row) => !u.isActive && !u.lastLoginAt;
async function person(u: Row, opts: { admins: Set<string>; seal: (v: string) => string; keepAccountsNotices: boolean }): Promise<ImportPerson> {
const [acceptances, consents] = await Promise.all([
prisma.noticeAcceptance.findMany({ where: { userId: u.id }, select: { version: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 100 }),
prisma.communicationConsent.findMany({ where: { userId: u.id }, select: { channel: true, granted: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 500 }),
]);
const totp = u.twoFactorEnabled && u.twoFactorMethod === 'authenticator' && u.totpSecret ? (() => { try { return decrypt(u.totpSecret!); } catch { return null; } })() : null;
// An authenticator whose secret can't be read moves without 2FA rather than locking them out.
const twoFactor = !u.twoFactorEnabled ? null : u.twoFactorMethod === 'authenticator' ? (totp ? 'totp' as const : null) : u.twoFactorMethod === 'whatsapp' ? 'whatsapp' as const : 'email' as const;
const phone = u.phoneNumber && phoneSchema.safeParse(u.phoneNumber).success ? u.phoneNumber : null;
return {
id: u.id,
name: (u.name || '').trim().slice(0, 200) || u.email,
email: u.email.trim().toLowerCase(),
emailVerified: !!u.lastLoginAt,
phone,
passwordHash: !pendingActivation(u) && HASH.test(u.password) ? opts.seal(u.password) : null,
twoFactor: twoFactor === 'whatsapp' && !phone ? 'email' : twoFactor,
totpSecret: totp ? opts.seal(totp) : null,
totpLastStep: totp ? u.totpLastStep ?? null : null,
failedSignIns: Math.min(1000, Math.max(0, u.failedAttempts || 0)),
lockedUntil: iso(u.lockUntil),
news: { email: !!u.newsEmail, whatsapp: !!u.newsWhatsApp },
newsAskedAt: iso(u.newsAskedAt),
noticeVersionAccepted: opts.keepAccountsNotices ? 0 : toAccountsVersion(u.noticeVersionAccepted),
noticeAcceptances: opts.keepAccountsNotices ? [] : acceptances.map((a: { version: number; createdAt: Date }) => ({ version: a.version + 1, acceptedAt: iso(a.createdAt)! })),
consentChanges: consents.filter((c: { channel: string }) => c.channel === 'email' || c.channel === 'whatsapp').map((c: { channel: 'email' | 'whatsapp'; granted: boolean; createdAt: Date }) => ({ channel: c.channel, granted: c.granted, at: iso(c.createdAt)! })),
lastSignInAt: iso(u.lastLoginAt),
status: u.isActive || pendingActivation(u) ? 'active' : 'deactivated',
admin: opts.admins.has(u.id) && u.role === 'admin',
createdAt: iso(u.createdAt)!,
};
}
/** Events' published notice versions, as Accounts numbers them. */
async function notices() {
const rows: { version: number; sections: unknown; publishedAt: Date }[] = await prisma.privacyNotice.findMany({ orderBy: { version: 'asc' }, take: 100 });
return rows.map((n) => {
const sections = Array.isArray(n.sections) ? (n.sections as { title?: string; body?: string }[]) : [];
const body = sections.map((s) => [s.title ? `${s.title}` : '', s.body ?? ''].filter(Boolean).join('\n\n')).join('\n\n').slice(0, 200_000) || 'Privacy notice';
return { version: n.version + 1, title: 'Privacy notice', body, publishedAt: iso(n.publishedAt)! };
});
}
function versionAtLeast(v: string, min: number[]) {
const parts = String(v).split('.').map((x) => parseInt(x, 10) || 0);
for (let i = 0; i < min.length; i++) {
if ((parts[i] ?? 0) !== min[i]) return (parts[i] ?? 0) > min[i]!;
}
return true;
}
const chunk = <T,>(list: T[], n: number) => Array.from({ length: Math.ceil(list.length / n) }, (_, i) => list.slice(i * n, i * n + n));
export type MoveSummary = {
mode: 'local' | 'accounts';
accountsConnected: boolean;
accountsUrl: string | null;
movedAt: string | null;
undoUntil: string | null;
secretsCleared: boolean;
running: boolean;
report: unknown;
};
export async function status(): Promise<MoveSummary> {
const [mode, link, movedAt, cleared, report, running] = await Promise.all([authMode(), accountsLink(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY), getSetting(REPORT_KEY), getSetting(RUNNING_KEY)]);
const undoUntil = movedAt && !cleared ? new Date(new Date(movedAt).getTime() + UNDO_DAYS * 86400e3).toISOString() : null;
return {
mode, accountsConnected: !!link, accountsUrl: link?.url ?? null, movedAt, undoUntil, secretsCleared: !!cleared,
running: !!running && Date.now() - new Date(running).getTime() < 30 * 60e3,
report: report ? JSON.parse(report) : null,
};
}
export type CheckResult = {
accountsVersion: string;
toMove: number;
wouldCreate: number;
wouldLink: { name: string; email: string }[];
refused: { name: string; email: string; reason: string }[];
skipped: number;
admins: { id: string; name: string; email: string }[];
noticeConflict: { accountsVersions: number[]; eventsVersions: number[] } | null;
withTwoFactor: number;
/** 3.1.0: what Accounts can send. The move needs email (codes and password links); WhatsApp codes go by email when WhatsApp can't. */
messaging: { email: boolean; whatsapp: boolean; whatsappTwoFactor: number };
};
async function connected() {
if ((await authMode()) === 'accounts') throw new MoveError('Sign-in already goes through Accounts.', 'ALREADY_MOVED');
try {
return await accounts();
} catch (e) {
if (e instanceof AccountsUnavailable) throw new MoveError(e.message, 'ACCOUNTS_UNAVAILABLE', 503);
throw e;
}
}
/** The dry run: nothing is written, here or in Accounts. */
export async function check(): Promise<CheckResult> {
const auth = await connected();
const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: await churchLook() });
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) {
throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later. Update Accounts first.`, 'ACCOUNTS_TOO_OLD');
}
const people = await peopleToMove();
const seal = (v: string) => auth.seal(v);
const byId = new Map(people.map((p) => [p.id, p]));
const results: ImportResult[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal, keepAccountsNotices: false })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: null, check: true, people: built });
results.push(...r.results);
}
const eventsNotices = await notices();
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
return {
accountsVersion: begin.accountsVersion,
toMove: people.length,
wouldCreate: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
wouldLink: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
skipped: await skippedCount(),
admins: people.filter((p) => p.role === 'admin').map((p) => ({ id: p.id, name: p.name, email: p.email })),
noticeConflict: !begin.noticesTaken && eventsNotices.length ? { accountsVersions: begin.accountsNoticeVersions, eventsVersions: eventsNotices.map((n) => n.version - 1) } : null,
withTwoFactor: people.filter((p) => p.twoFactorEnabled).length,
messaging: await messagingNow(people),
};
}
async function messagingNow(people: Row[]) {
const status = await accountsMessaging();
return { email: status.email.ready, whatsapp: status.whatsapp.ready, whatsappTwoFactor: people.filter((p) => p.twoFactorEnabled && p.twoFactorMethod === 'whatsapp').length };
}
export type MoveReport = {
movedAt: string;
by: string;
created: number;
linked: { name: string; email: string }[];
refused: { name: string; email: string; reason: string }[];
skipped: number;
accountsAdmins: { name: string; email: string }[];
notices: 'events' | 'accounts';
};
/**
* Ends a move: Accounts checks it holds every account this site now relies on (everyone linked,
* including a move run again after a failure, and people who signed up through Accounts since).
*/
async function finishMove(auth: Awaited<ReturnType<typeof accounts>>, actor: string | null) {
const linkedRows: { accountId: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { accountId: true } });
const subs = [...new Set(linkedRows.map((x) => x.accountId))];
const finish = await auth.request<{ matched: boolean; count: number; missing: string[] }>({ type: 'import.finish', actor, subs });
if (!finish.matched) {
throw new MoveError(`Accounts holds ${finish.count} of the ${subs.length} people this site relies on (missing, for example, ${finish.missing.slice(0, 3).join(', ')}). Nothing was switched; run the move again.`, 'MISMATCH');
}
}
/**
* People added here after sign-in moved, without signing in through Accounts (demo data, an
* import): moved into Accounts the same way, so they can sign in. Only while sign-in goes through
* Accounts; returns how many were moved.
*/
export async function moveNewPeople(actor: string | null = null): Promise<{ moved: number; refused: { email: string; reason: string }[] }> {
if ((await authMode()) !== 'accounts') return { moved: 0, refused: [] };
const people = await peopleToMove();
if (!people.length) return { moved: 0, refused: [] };
const auth = await accounts();
await auth.request({ type: 'import.begin', actor, check: false, notices: [], church: { name: null, primaryColour: null } });
try {
const byId = new Map(people.map((p) => [p.id, p]));
let moved = 0;
const refused: { email: string; reason: string }[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal: (v) => auth.seal(v), keepAccountsNotices: false })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor, check: false, people: built }, { timeoutMs: 120000 });
for (const res of r.results) {
if (res.sub && res.outcome !== 'refused') {
await prisma.user.update({ where: { id: res.id }, data: { accountId: res.sub } });
moved++;
} else refused.push({ email: byId.get(res.id)?.email ?? res.id, reason: res.reason ?? '' });
}
}
await finishMove(auth, actor);
return { moved, refused };
} catch (e) {
await auth.request({ type: 'import.abort', actor }).catch(() => {});
throw e;
}
}
/**
* 3.3.0: new demo data replaced the old (set-demo), so the old demo people's church accounts go
* too (contracts 1.11.0 `people.removeDemo`). Accounts removes only demo addresses
* (`@example.com`) it knows through this site, never an Accounts admin. Only while sign-in goes
* through Accounts; returns how many went and how many it kept.
*/
export async function removeDemoPeople(subs: string[], actor: string | null = null): Promise<{ removed: number; kept: number }> {
const unique = [...new Set(subs.filter(Boolean))];
if ((await authMode()) !== 'accounts' || !unique.length) return { removed: 0, kept: 0 };
const auth = await accounts();
let removed = 0;
let kept = 0;
for (const batch of chunk(unique, REMOVE_DEMO_MAX)) {
const r = await auth.request<{ removed: number; kept: unknown[] }>({ type: 'people.removeDemo', actor, subs: batch }, { timeoutMs: 120000 });
removed += r.removed;
kept += r.kept.length;
}
return { removed, kept };
}
/** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */
export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise<MoveReport> {
const auth = await connected();
// 3.1.0: without email in Accounts nobody can get a code or a password link there, so nobody
// could sign in after the move. Set it up first (Settings → Sign-in → Email and WhatsApp).
const messaging = await accountsMessaging();
if (!messaging.email.ready) {
throw new MoveError("The church's Accounts can't send email yet, so people couldn't get their sign-in codes or password links there. Set up its email first (copy this site's, test it, save it), then move.", 'EMAIL_NOT_READY');
}
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) throw new MoveError('A move is already running.', 'RUNNING');
await setSetting(RUNNING_KEY, new Date().toISOString());
const audit = (action: string, metadata: object) => logAdminAction({ actorId: opts.actor.id, actorRole: opts.actor.role, action, targetType: 'setting', targetId: MODE_KEY, metadata, ip: opts.ip ?? null });
await audit('sign_in_move_started', { adminIds: opts.adminIds });
let begun = false;
try {
const eventsNotices = await notices();
const begin = await auth.request<{ noticesTaken: boolean; accountsVersion: string }>({
type: 'import.begin', actor: opts.actor.id, check: false, notices: opts.keepAccountsNotices ? [] : eventsNotices, church: await churchLook(),
});
begun = true;
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later.`, 'ACCOUNTS_TOO_OLD');
if (!begin.noticesTaken && eventsNotices.length && !opts.keepAccountsNotices) {
throw new MoveError('Accounts already has its own privacy notice. Choose which notice to keep, then move again.', 'NOTICE_CONFLICT');
}
const people = await peopleToMove();
const byId = new Map(people.map((p) => [p.id, p]));
const admins = new Set(opts.adminIds);
const results: ImportResult[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins, seal: (v) => auth.seal(v), keepAccountsNotices: !!opts.keepAccountsNotices })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: opts.actor.id, check: false, people: built }, { timeoutMs: 120000 });
for (const res of r.results) {
if (res.sub && res.outcome !== 'refused') await prisma.user.update({ where: { id: res.id }, data: { accountId: res.sub } });
}
results.push(...r.results);
}
await finishMove(auth, opts.actor.id);
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
const report: MoveReport = {
movedAt: new Date().toISOString(),
by: opts.actor.name ?? opts.actor.id,
created: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
linked: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
skipped: await skippedCount(),
accountsAdmins: people.filter((p) => admins.has(p.id) && p.role === 'admin').map((p) => ({ name: p.name, email: p.email })),
notices: opts.keepAccountsNotices ? 'accounts' : 'events',
};
await setSetting(REPORT_KEY, JSON.stringify(report));
await setSetting(MOVED_AT_KEY, report.movedAt);
await setSetting(CLEARED_KEY, null);
await setSetting(MODE_KEY, 'accounts');
await audit('sign_in_move_finished', { created: report.created, linked: report.linked.length, refused: report.refused.length, skipped: report.skipped });
emailReport(opts.actor.id, report).catch(() => {});
return report;
} catch (e) {
if (begun) await auth.request({ type: 'import.abort', actor: opts.actor.id }).catch(() => {});
await audit('sign_in_move_failed', { message: (e as Error).message });
if (e instanceof MoveError) throw e;
throw new MoveError(`The move stopped: ${(e as Error).message}. Nothing was switched; you can run it again.`, (e as { code?: string }).code ?? 'MOVE_FAILED', 502);
} finally {
await setSetting(RUNNING_KEY, null);
}
}
async function emailReport(actorId: string, report: MoveReport) {
const admin = await prisma.user.findUnique({ where: { id: actorId }, select: { email: true, name: true } });
if (!admin?.email || NOT_MOVED.test(admin.email)) return;
const { sendMail } = require('../utils/email') as { sendMail(m: object): Promise<void> };
const lines = [
`Hello ${admin.name || 'there'},`,
'',
`Sign-in for ${await siteUrl()} now goes through your church's Accounts.`,
'',
`Moved: ${report.created}`,
`Linked to an account they already had: ${report.linked.length}${report.linked.length ? ` (${report.linked.map((l) => l.email).join(', ')})` : ''}`,
`Not moved: ${report.refused.length}${report.refused.length ? ` (${report.refused.map((r) => `${r.email}: ${r.reason}`).join('; ')})` : ''}`,
`Guests and deleted people (stay in Cross Events only): ${report.skipped}`,
`Also Accounts admins: ${report.accountsAdmins.map((a) => a.name).join(', ') || 'nobody'}`,
'',
`You can undo this under Settings → Sign-in for ${UNDO_DAYS} days.`,
];
await sendMail({ to: admin.email, subject: 'Sign-in has moved to your church\'s Accounts', text: lines.join('\n'), html: lines.map((l) => (l ? `<p>${l.replace(/</g, '&lt;')}</p>` : '')).join('') });
}
export async function undo(actor: { id: string; role: string }, ip: string | null = null) {
const s = await status();
if (s.mode !== 'accounts') throw new MoveError('Sign-in is already in Cross Events.', 'NOT_MOVED');
if (!s.undoUntil || new Date(s.undoUntil) < new Date()) throw new MoveError(`Undo was possible for ${UNDO_DAYS} days after the move; the old passwords have been removed since.`, 'TOO_LATE');
await setSetting(MODE_KEY, 'local');
await logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'sign_in_move_undone', targetType: 'setting', targetId: MODE_KEY, metadata: { movedAt: s.movedAt }, ip });
return status();
}
/** The `accounts-secrets` job: 14 days after the move, Events stops holding passwords and 2FA secrets. */
export async function clearOldSecrets(now = new Date()) {
const [mode, movedAt, cleared] = await Promise.all([authMode(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY)]);
if (mode !== 'accounts' || !movedAt || cleared) return { cleared: 0 };
if (now.getTime() - new Date(movedAt).getTime() < UNDO_DAYS * 86400e3) return { cleared: 0 };
const linked: { id: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { id: true } });
const ids = linked.map((u) => u.id);
for (const id of ids) {
await prisma.user.update({ where: { id }, data: { password: `!accounts:${crypto.randomBytes(12).toString('hex')}`, totpSecret: null, totpLastStep: null } });
}
await prisma.recoveryCode.deleteMany({ where: { userId: { in: ids } } });
await prisma.trustedDevice.deleteMany({ where: { userId: { in: ids } } });
await prisma.passwordReset.updateMany({ where: { userId: { in: ids }, used: false }, data: { used: true } });
await setSetting(CLEARED_KEY, now.toISOString());
await logAdminAction({ actorId: null, actorRole: 'system', action: 'sign_in_secrets_cleared', targetType: 'setting', targetId: MODE_KEY, metadata: { people: ids.length } });
return { cleared: ids.length };
}
+25
View File
@@ -0,0 +1,25 @@
/**
* News consent lives in the church's Accounts once sign-in goes through it (3.0.0,
* docs/EVENTS-3.0-PLAN.md decision 7). An unsubscribe link or a WhatsApp STOP here turns news off
* there too (`people.newsOff`), so it's off for every product, and Accounts' next `user.updated`
* doesn't turn it back on here. Never fails the unsubscribe itself.
*/
import { accounts } from './client';
import { viaAccounts } from './mode';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
export async function newsOffInAccounts(userId: string, channels: string[]): Promise<void> {
try {
if (!(await viaAccounts())) return;
const u = await prisma.user.findUnique({ where: { id: userId }, select: { accountId: true } });
if (!u?.accountId) return;
const both = channels.includes('email') && channels.includes('whatsapp');
const channel = both ? 'all' : channels.includes('whatsapp') ? 'whatsapp' : 'email';
await (await accounts()).request({ type: 'people.newsOff', actor: null, sub: u.accountId, channel });
} catch (e) {
console.warn('[accounts] news off not passed on:', (e as Error).message);
}
}
@@ -0,0 +1,102 @@
/**
* The nightly people check (3.6.0, contracts 1.14.0 `people.check`, Accounts 1.5.0): Accounts tells
* Events about every change (`user.updated`, `user.deleted`), retried for about a week; this catches
* whatever never arrived (a link that was down, as after a demo load before 3.5.0). For everyone here
* with an account it asks Accounts, a page at a time, and:
*
* - updates the local copy when the profile differs (as `user.updated` does);
* - handles a deleted account as `user.deleted` does (anonymised, or deferred while the person has a
* registration for an event that hasn't ended);
* - only counts people Accounts doesn't know through this site (`unknown`). When most of a page is
* unknown, Events is probably linked to the wrong Accounts: the check stops and fails, so it
* shows on Background jobs and the Hub, and nothing is changed for those people.
*/
import { PEOPLE_CHECK_MAX, peopleCheckReplySchema, type PeopleCheckReply, type Profile } from '@crosscode/contracts';
import { accounts, accountsLink } from './client';
import { handleAccountsCall } from './calls';
import { viaAccounts } from './mode';
import { recordSignInError } from './status';
import { updateLocalCopy } from './signin';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
type Local = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
export type PeopleCheckResult = { checked: number; updated: number; deleted: number; deferred: number; deactivated: number; unknown: number } | { skipped: string };
/** Asks Accounts about these subs (tests replace it). */
export type Ask = (subs: string[]) => Promise<PeopleCheckReply>;
const defaultAsk: Ask = async (subs) => {
const auth = await accounts();
const raw = await auth.request({ type: 'people.check', actor: null, subs }, { timeoutMs: 120000 });
return peopleCheckReplySchema.parse(raw);
};
/** Whether the local copy already says what the profile says (only what Events keeps). */
export function sameAsLocal(u: Local, p: Profile): boolean {
return u.name === p.name
&& u.email.toLowerCase() === p.email.toLowerCase()
&& (u.phoneNumber ?? null) === (p.phone_number ?? null)
&& u.newsEmail === p.news_consent.email
&& u.newsWhatsApp === p.news_consent.whatsapp;
}
/** More than this share of a page unknown (with at least MIN_FOR_ALARM people) stops the check. */
const UNKNOWN_ALARM = 0.5;
const MIN_FOR_ALARM = 10;
export async function runPeopleCheck(opts: { ask?: Ask; pageSize?: number } = {}): Promise<PeopleCheckResult> {
if (!(await viaAccounts())) return { skipped: 'This site uses its own sign-in.' };
if (!(await accountsLink())) return { skipped: 'Accounts isn\'t linked.' };
const ask = opts.ask ?? defaultAsk;
const size = Math.min(opts.pageSize ?? PEOPLE_CHECK_MAX, PEOPLE_CHECK_MAX);
const out = { checked: 0, updated: 0, deleted: 0, deferred: 0, deactivated: 0, unknown: 0 };
let cursor: string | undefined;
for (;;) {
const page: Local[] = await prisma.user.findMany({
where: { accountId: { not: null } },
select: { id: true, accountId: true, name: true, email: true, phoneNumber: true, newsEmail: true, newsWhatsApp: true },
orderBy: { id: 'asc' },
take: size,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
});
if (!page.length) break;
cursor = page[page.length - 1]!.id;
const bySub = new Map(page.map((u) => [u.accountId, u]));
let reply: PeopleCheckReply;
try {
reply = await ask(page.map((u) => u.accountId));
} catch (e) {
// Accounts before 1.5.0 doesn't know people.check: nothing to do until it's updated.
const err = e as { code?: string; message?: string };
if (err.code === 'INVALID_REQUEST' && /\btype\b/.test(err.message ?? '')) return { skipped: 'The church\'s Accounts is older than 1.5.0, which this check needs.' };
throw e;
}
const unknown = reply.people.filter((p) => p.status === 'unknown').length;
if (page.length >= MIN_FOR_ALARM && unknown / page.length > UNKNOWN_ALARM) {
const message = `Accounts doesn't know ${unknown} of ${page.length} people here: is this site linked to the church's own Accounts? Nothing was changed for them.`;
await recordSignInError('PEOPLE_UNKNOWN', message);
throw new Error(message);
}
for (const p of reply.people) {
const u = bySub.get(p.sub);
if (!u) continue; // not one we asked about
out.checked++;
if (p.status === 'unknown') { out.unknown++; continue; }
if (p.status === 'deleted') {
const r = await handleAccountsCall({ type: 'user.deleted', sub: p.sub } as never) as { status?: string };
if (r.status === 'deferred') out.deferred++; else out.deleted++;
continue;
}
if (p.status === 'deactivated') out.deactivated++;
if (p.profile && !sameAsLocal(u, p.profile)) {
await updateLocalCopy(u.id, p.profile);
out.updated++;
}
}
if (page.length < size) break;
}
return out;
}
+289
View File
@@ -0,0 +1,289 @@
/**
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3), under /api:
*
* GET /auth/signin?returnTo=…[&signup=1][&mfa=1] start: PKCE + state, a pending cookie, off to Accounts
* GET /auth/callback back from Accounts: find or link the user, then
* /auth/complete#<one-time code>
* POST /auth/handoff { code } the page swaps the code for Events' own token
* POST /auth/signout ends Events' sessions; answers Accounts' sign-out address
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
*
* Events keeps its own session (the 30-day token with `tokenVersion`), so the rest of the API is
* unchanged; only how a token is obtained changes. The token carries `asi` (this sign-in's row) and
* `mfa` (whether Accounts asked for a second step), which `protect` checks for staff roles.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import { ACCOUNTS_CALL_PATH, OIDC_CLIENT_PATHS, safeReturnPath, type IdentityClaims } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, AccountsUnavailable } from './client';
import { viaAccounts } from './mode';
import { handleAccountsCall } from './calls';
import { clearSignInError, recordSignInError } from './status';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { generateToken } = require('../config/auth') as { generateToken(id: string, role: string, v: number, extra?: object): string };
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
const PENDING_COOKIE = 'ev_signin';
const MFA_COOKIE = 'ev_signin_mfa';
const COOKIE_PATH = '/api/auth';
const PENDING_MINUTES = 10;
const HANDOFF_SECONDS = 60;
const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
function cookies(req: Request): Record<string, string> {
const out: Record<string, string> = {};
for (const part of String(req.headers.cookie || '').split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
const cookieOptions = () => ({ httpOnly: true, sameSite: 'lax' as const, secure: process.env.NODE_ENV === 'production', path: COOKIE_PATH });
/** A page of this site (absolute: in development the API and the pages are on different ports). */
async function page(path: string): Promise<string> {
return `${(await siteUrl()).replace(/\/+$/, '')}${path}`;
}
/** Where a problem page sends people: a short reason and "Try again" with the same return path. */
const problem = async (res: Response, code: string, returnTo = '/') =>
res.redirect(303, await page(`/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
/** A placeholder for `User.password` (required by the schema): never a valid hash, so never a password. */
const NO_PASSWORD = () => `!accounts:${crypto.randomBytes(12).toString('hex')}`;
type EventsUser = { id: string; name: string; email: string; role: string; tokenVersion: number; isActive: boolean; accountId: string | null; phoneNumber: string | null };
const USER_SELECT = { id: true, name: true, email: true, role: true, tokenVersion: true, isActive: true, accountId: true, phoneNumber: true } as const;
const isGuestEmail = (e: string) => /@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e);
/**
* The Events user for an Accounts sign-in (§2): by `accountId`; else a user (often a guest
* record from the door) with the same **verified** email that isn't linked yet; else a new `user`.
*/
export async function userForClaims(claims: IdentityClaims): Promise<{ user: EventsUser | null; problem?: string; linked?: boolean; created?: boolean }> {
const byAccount = await prisma.user.findUnique({ where: { accountId: claims.sub }, select: USER_SELECT });
if (byAccount) return { user: byAccount };
const email = claims.email.toLowerCase();
const byEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' } }, select: USER_SELECT });
if (byEmail) {
if (byEmail.accountId) return { user: null, problem: 'EMAIL_IN_USE' };
if (!claims.email_verified) return { user: null, problem: 'EMAIL_NOT_VERIFIED' };
const linked = await prisma.user.update({ where: { id: byEmail.id }, data: { accountId: claims.sub }, select: USER_SELECT });
return { user: linked, linked: true };
}
// New to Events. Its id is the sub when that's free, as for everyone moved in.
const taken = await prisma.user.findUnique({ where: { id: claims.sub }, select: { id: true } });
const created = await prisma.user.create({
data: {
...(taken ? {} : { id: claims.sub }),
accountId: claims.sub,
name: claims.name,
email,
password: NO_PASSWORD(),
role: 'user',
isActive: true,
tokenVersion: 0,
newsEmail: claims.news_consent.email,
newsWhatsApp: claims.news_consent.whatsapp,
newsAskedAt: new Date(),
// Accounts' notice versions are Events' + 1 (its built-in notice is 1, Events' is 0).
noticeVersionAccepted: Math.max(0, claims.privacy_notice_version - 1),
},
select: USER_SELECT,
});
return { user: created, created: true };
}
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
const data: Record<string, unknown> = {
name: profile.name,
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
...(profile.two_factor !== undefined ? { twoFactorEnabled: profile.two_factor !== null, twoFactorMethod: profile.two_factor === 'totp' ? 'authenticator' : profile.two_factor } : {}),
newsEmail: profile.news_consent.email,
newsWhatsApp: profile.news_consent.whatsapp,
...(profile.privacy_notice_version ? { noticeVersionAccepted: Math.max(0, profile.privacy_notice_version - 1) } : {}),
};
const email = profile.email.toLowerCase();
const sameEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' }, NOT: { id: userId } }, select: { id: true } });
if (!sameEmail && !isGuestEmail(email)) data.email = email;
if (profile.phone_number) {
const samePhone = await prisma.user.findFirst({ where: { phoneNumber: profile.phone_number, NOT: { id: userId } }, select: { id: true } });
if (!samePhone) data.phoneNumber = profile.phone_number;
} else {
data.phoneNumber = null;
}
await prisma.user.update({ where: { id: userId }, data });
}
async function startSignIn(req: Request, res: Response) {
const returnTo = safeReturnPath(req.query.returnTo);
if (!(await viaAccounts())) return res.redirect(303, await page(`/login?redirect=${encodeURIComponent(returnTo)}&local=1`));
try {
const auth = await accounts();
const requireTwoFactor = req.query.mfa === '1';
const { url, cookie } = await auth.startSignIn(returnTo, {
requireTwoFactor,
signUp: req.query.signup === '1',
...(typeof req.query.email === 'string' && req.query.email.length < 200 ? { loginHint: req.query.email } : {}),
});
res.cookie(PENDING_COOKIE, cookie, { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
else res.clearCookie(MFA_COOKIE, cookieOptions());
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
const failed = e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED';
// 3.5.0: the reason goes to the Hub with the next heartbeat (the page only says "try again").
await recordSignInError(failed, (e as Error).message);
return problem(res, failed, returnTo);
}
}
async function callback(req: Request, res: Response) {
const jar = cookies(req);
const askedMfa = jar[MFA_COOKIE] === '1';
res.clearCookie(PENDING_COOKIE, cookieOptions());
res.clearCookie(MFA_COOKIE, cookieOptions());
// Cancelled at Accounts: back to the home page, signed out.
if (req.query.error === 'access_denied') return res.redirect(303, await page('/'));
let auth;
try {
auth = await accounts();
} catch (e) {
await recordSignInError('ACCOUNTS_UNAVAILABLE', (e as Error).message);
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
try {
// The address Accounts sent the browser to, as it registered it (never the backend's own port).
signed = await auth.finishSignIn(`${(await siteUrl()).replace(/\/+$/, '')}${req.originalUrl}`, jar[PENDING_COOKIE]);
} catch (e) {
const code = (e as { code?: string }).code;
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
if (code !== 'NO_PENDING') await recordSignInError('FINISH_FAILED', (e as Error).message);
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
}
await clearSignInError();
const { claims, returnTo, idToken } = signed;
const found = await userForClaims(claims);
if (!found.user) return problem(res, found.problem ?? 'NO_USER', returnTo);
const user = found.user;
if (!user.isActive) return problem(res, 'EVENTS_OFF', returnTo);
// Staff roles need a second step (§3): ask Accounts for it once; a second miss is a problem.
const mfa = claims.amr.includes('mfa');
if (requiresTwoFactor(user) && !mfa) {
if (askedMfa) return problem(res, 'MFA_REQUIRED', returnTo);
return res.redirect(303, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`);
}
await updateLocalCopy(user.id, claims).catch((e: Error) => console.warn('[accounts] profile copy:', e.message));
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {});
logSecurityEvent({ userId: user.id, type: 'login', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
const code = crypto.randomBytes(32).toString('base64url');
const sid = (claims as unknown as { sid?: string }).sid ?? null;
await prisma.accountsSignIn.create({
data: { userId: user.id, codeHash: hash(code), codeUsedAt: null, codeExpires: new Date(Date.now() + HANDOFF_SECONDS * 1000), returnTo, idToken: encrypt(idToken), sid, mfa },
});
return res.redirect(303, await page(`/auth/complete#${code}`));
}
async function handoff(req: Request, res: Response) {
const code = typeof req.body?.code === 'string' ? req.body.code : '';
const row = code ? await prisma.accountsSignIn.findUnique({ where: { codeHash: hash(code) } }) : null;
if (!row || row.codeUsedAt || !row.codeExpires || row.codeExpires < new Date()) {
return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
}
// Single use, whatever happens next.
const used = await prisma.accountsSignIn.updateMany({ where: { id: row.id, codeUsedAt: null }, data: { codeUsedAt: new Date(), codeHash: null } });
if (!used.count) return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
const user = await prisma.user.findUnique({ where: { id: row.userId }, select: USER_SELECT });
if (!user || !user.isActive) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Please sign in again.' } });
return res.json({
data: {
status: 'signed_in',
token: generateToken(user.id, user.role, user.tokenVersion, { asi: row.id, mfa: row.mfa }),
user: { id: user.id, name: user.name, email: user.email, role: user.role },
newsPromptPending: false,
noticePromptPending: false,
returnTo: safeReturnPath(row.returnTo),
},
});
}
/** Ends this person's Events sessions (every token they hold stops working at the next request). */
export async function endEventsSessions(userId: string) {
await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
}
async function signOut(req: Request, res: Response) {
// `protect` ran: req.user is the person; the token's `asi` finds the ID token for Accounts.
const user = (req as unknown as { user?: { id: string } }).user;
const asi = (req as unknown as { tokenClaims?: { asi?: string } }).tokenClaims?.asi;
if (!user) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Not signed in.' } });
await endEventsSessions(user.id);
let url: string | null = null;
if (await viaAccounts()) {
try {
const row = asi ? await prisma.accountsSignIn.findUnique({ where: { id: asi } }) : null;
const idToken = row?.idToken ? (() => { try { return decrypt(row.idToken); } catch { return undefined; } })() : undefined;
url = (await accounts()).signOutUrl(idToken);
} catch (e) {
console.warn('[accounts] sign-out address:', (e as Error).message);
}
}
return res.json({ data: { signedOut: true, url } });
}
async function backchannelLogout(req: Request, res: Response) {
try {
const { sub } = await (await accounts()).verifyLogoutToken(String(req.body?.logout_token ?? ''));
const user = await prisma.user.findUnique({ where: { accountId: sub }, select: { id: true } });
if (user) await endEventsSessions(user.id);
return res.status(200).end();
} catch (e) {
console.warn('[accounts] back-channel logout refused:', (e as Error).message);
return res.status(400).json({ error: 'invalid_request' });
}
}
async function accountsCall(req: Request, res: Response) {
try {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const call = (await accounts()).verifyAccountsCall(raw, req.headers as Record<string, string | string[] | undefined>);
return res.json(await handleAccountsCall(call));
} catch (e) {
const err = e as { code?: string; message: string; status?: number };
const status = err.code === 'BAD_SIGNATURE' || err.code === 'STALE_REQUEST' ? 401 : err.code === 'INVALID_REQUEST' ? 400 : err.status ?? 500;
if (status >= 500) console.warn('[accounts] call failed:', err.message);
return res.status(status).json({ message: err.message, code: err.code ?? 'SERVER_ERROR' });
}
}
/** Mounted at /api before express.json (the Accounts calls need the exact bytes). */
export function accountsRouter(protect: express.RequestHandler) {
const r = express.Router();
const strip = (p: string) => p.replace(/^\/api/, '');
r.get('/auth/signin', startSignIn);
r.get(strip(OIDC_CLIENT_PATHS.callback), callback);
r.post('/auth/handoff', express.json({ limit: '4kb' }), handoff);
r.post('/auth/signout', express.json({ limit: '4kb' }), protect, signOut);
r.post(strip(OIDC_CLIENT_PATHS.backchannelLogout), express.urlencoded({ extended: false, limit: '16kb' }), backchannelLogout);
r.post(strip(ACCOUNTS_CALL_PATH), express.raw({ type: () => true, limit: '256kb' }), accountsCall);
return r;
}
@@ -0,0 +1,32 @@
/**
* How people sign in here, for the Hub (3.5.0, heartbeat `stats.signIn`, contracts 1.13.0): the
* mode, the Accounts this site is linked to, and the last sign-in that failed to start or finish.
* A site in `accounts` mode without a link can't sign anyone in; the Hub raises an alert for it.
*/
import { accountsLink } from './client';
import { authMode, getSetting, setSetting } from './mode';
export const LAST_ERROR_KEY = 'accounts_last_signin_error';
type LastError = { at: string; code: string; message: string };
/** Keeps the last failure (a code and a sentence; never tokens or cookies). */
export async function recordSignInError(code: string, message: string, now = new Date()): Promise<void> {
const value: LastError = { at: now.toISOString(), code: code.slice(0, 60), message: message.replace(/\s+/g, ' ').slice(0, 500) };
await setSetting(LAST_ERROR_KEY, JSON.stringify(value)).catch(() => {});
}
/** A sign-in that worked clears it. */
export async function clearSignInError(): Promise<void> {
if (await getSetting(LAST_ERROR_KEY).catch(() => null)) await setSetting(LAST_ERROR_KEY, null).catch(() => {});
}
export async function signInStatus(): Promise<{ mode: 'local' | 'accounts'; accounts: { installId: string; url: string } | null; lastError: LastError | null }> {
const [mode, link, raw] = await Promise.all([authMode(), accountsLink(), getSetting(LAST_ERROR_KEY).catch(() => null)]);
let lastError: LastError | null = null;
try {
const parsed = raw ? JSON.parse(raw) : null;
if (parsed && typeof parsed.at === 'string' && typeof parsed.code === 'string' && typeof parsed.message === 'string') lastError = parsed;
} catch { /* an unreadable value is no error */ }
return { mode, accounts: link ? { installId: link.installId, url: link.url } : null, lastError };
}
+9 -10
View File
@@ -138,6 +138,9 @@ app.use('/api/v2/webhooks', webhooksRouter);
// The church's other products (2.4.0): the event feed, event.changed and Connect
// (/api/feed/v1, /api/links/v1; src/links/routes.ts). Its own parsers (raw for the webhook).
app.use('/api', require('./links/routes').crossProductRouter());
// 3.0.0: signing in through the church's Accounts (/api/auth/*, Accounts' calls at
// /api/accounts/v1/events; src/accounts/signin.ts). Its own parsers (raw for Accounts' calls).
app.use('/api', require('./accounts/signin').accountsRouter(require('./middleware/authMiddleware').protect));
// Apply JSON body parser for all non-webhook routes
app.use(express.json());
@@ -146,6 +149,9 @@ app.use((req, res, next) => {
if (req.body === undefined) req.body = {};
next();
});
// 3.0.0: once sign-in goes through Accounts, Events' own sign-in, password and 2FA endpoints say
// where to go instead, and profile changes go to Accounts (src/accounts/guard.ts).
app.use((req, res, next) => { require('./accounts/guard').signInGuard(req, res, next).catch(next); });
// Count server errors (any 5xx response) for the Hub heartbeat.
app.use((req, res, next) => {
@@ -190,18 +196,11 @@ app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
// Pre-warm the settings cache so synchronous helpers have DB values from startup
const { getSettingSync, warmCache } = require('./utils/settingsCache');
warmCache().catch(() => {});
// Uploaded branding assets can include SVGs, which may embed <script>/event
// handlers. Serving them inline lets a compromised/malicious upload run script
// in the site's origin if opened directly, so pin the safe response headers
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
// Uploaded files, with safe headers (utils/uploads.js): served from the folder they're saved in
// (3.3.0; before, from one relative to where the process started, so a new logo could be "missing").
// Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl).
// /uploads still answers for links made before 2.2.0.
const uploads = express.static('public/uploads', {
setHeaders: (res) => {
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
res.setHeader('X-Content-Type-Options', 'nosniff');
},
});
const uploads = require('./utils/uploads').serveUploads();
app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed"
app.use('/uploads', uploads);
@@ -31,4 +31,22 @@ const runJobNow = async (req, res) => {
}
};
module.exports = { listJobs, runJobNow };
// @desc Switch a background job on or off, or change its schedule (3.4.0). Wins over the .env;
// null for either goes back to the .env.
// @route PUT /api/admin/jobs/:name
// @access Private/Admin
const updateJob = async (req, res) => {
try {
const body = req.body || {};
const choice = await jobs.setOverride(req.params.name, { enabled: body.enabled, cron: body.cron });
logAdminAction({
actorId: req.user.id, actorRole: req.user.role, action: 'job_settings_changed',
targetType: 'Job', targetId: req.params.name, metadata: { enabled: body.enabled, cron: body.cron }, ip: getClientIp(req),
});
res.json({ name: req.params.name, override: choice });
} catch (error) {
res.status(error.statusCode || 500).json({ message: safeErrorMessage(error) });
}
};
module.exports = { listJobs, runJobNow, updateJob };
@@ -2,6 +2,7 @@ const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const multer = require('multer');
const { UPLOADS_DIR } = require('../utils/uploads');
// Builds a filename multer can never be tricked into escaping the upload
// directory with — extension only, no attacker-controlled path segments.
@@ -13,7 +14,7 @@ function safeFilename(prefix, ext) {
// Setup multer storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..','public', 'uploads', 'events');
const uploadPath = path.join(UPLOADS_DIR, 'events');
// Check if the upload location exists
try {
@@ -52,7 +53,7 @@ const upload = multer({
// Logo storage (separate subfolder)
const logoStorage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'branding');
const uploadPath = path.join(UPLOADS_DIR, 'branding');
try {
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
@@ -80,7 +81,7 @@ const uploadLogo = multer({
// Favicon storage (same subfolder as the logo — both are "branding" assets)
const faviconStorage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'branding');
const uploadPath = path.join(UPLOADS_DIR, 'branding');
try {
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
+2
View File
@@ -245,6 +245,8 @@ async function heartbeat() {
try {
await store.saveLinkedProducts(data.linkedProducts);
if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus);
// 3.0.0: connect to the church's Accounts once the Hub lists it (accounts/autoConnect.ts).
require('../accounts/autoConnect').connectAccountsIfListed().catch((e) => console.warn('[accounts] Could not connect to Accounts yet:', e?.message || e));
} catch (e) {
console.warn('[hub] Could not save the linked products:', e?.message || e);
}
+25 -1
View File
@@ -58,6 +58,25 @@ async function pendingMigrations() {
}
}
/**
* 3.2.0: what's happening at the church now (heartbeat `stats.live`), so the Hub warns before an
* emergency update takes the site down: events with a session on now, or a one-day event (no
* sessions, at most 36 hours long) on now, each give or take 30 minutes; and tickets checked in
* during the last hour. A multi-week course without a session today doesn't count.
*/
async function liveNow(now = new Date()) {
const soon = new Date(now.getTime() + 30 * 60e3);
const recent = new Date(now.getTime() - 30 * 60e3);
const [sessions, plain, checkInsLastHour] = await Promise.all([
prisma.eventSession.findMany({ where: { cancelledAt: null, startsAt: { lte: soon }, endsAt: { gte: recent }, event: { isActive: true } }, select: { eventId: true } }),
prisma.event.findMany({ where: { isActive: true, startDate: { lte: soon }, endDate: { gte: recent }, sessions: { none: {} } }, select: { id: true, startDate: true, endDate: true } }),
prisma.ticketUsage.count({ where: { scannedAt: { gte: new Date(now.getTime() - 60 * 60e3) } } }),
]);
const ids = new Set(sessions.map(x => x.eventId));
for (const e of plain) if (new Date(e.endDate) - new Date(e.startDate) <= 36 * 60 * 60e3) ids.add(e.id);
return { eventsNow: ids.size, checkInsLastHour };
}
async function disk() {
try {
const s = await fs.promises.statfs(path.join(__dirname, '..', '..'));
@@ -123,11 +142,16 @@ async function stats(now = new Date()) {
prisma.payment.aggregate({ where: { createdAt: { gte: yearAgo }, ...EVENT_INCOME }, _sum: { amount: true } }),
require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []),
]);
const live = await liveNow(now).catch(() => undefined);
const campusesOn = await campusesEnabled().catch(() => false);
const campusCount = campusesOn ? await prisma.campus.count({ where: { archivedAt: null } }) : 0;
// 3.5.0: how people sign in (the Hub flags a site in Accounts mode without a link, or failing).
const signIn = await require('../accounts/status').signInStatus().catch(() => undefined);
return {
users,
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
...(live ? { live } : {}),
...(signIn ? { signIn } : {}),
registrations: { last30d: regs30, total: regsTotal },
tickets: { last30d: tickets30, total: ticketsTotal },
checkIns: { last30d: checkIns30 },
@@ -165,4 +189,4 @@ async function installInfo() {
};
}
module.exports = { APP_VERSION, incomeBand, health, stats, installInfo };
module.exports = { APP_VERSION, incomeBand, health, stats, installInfo, liveNow };
+177 -45
View File
@@ -10,7 +10,10 @@
*
* Each job can be switched off with its env flag (e.g. WAITLIST_JOB_ENABLED=false), and
* its schedule changed with JOB_SCHEDULE_<NAME> (cron, e.g. JOB_SCHEDULE_WAITLIST="*\/5 * * * *").
* JOBS_ENABLED=false turns all of them off (used by the end-to-end tests).
* 3.4.0: an admin can do both on the Background jobs page; their choice is kept in the database
* (AppSetting job_overrides), wins over the .env and takes effect straight away (other processes
* within 30 seconds).
* JOBS_ENABLED=false still turns all of them off (used by the end-to-end tests).
* If the queue can't start (e.g. the database user can't create the pgboss schema), the
* same jobs run on in-process timers instead, as before.
*/
@@ -95,6 +98,22 @@ const JOBS = [
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
},
{
// 3.6.0: catch any change from Accounts that never arrived (accounts/peopleCheck.ts).
name: 'accounts-people-check', label: 'Accounts: check everyone\'s details here match their church account', cron: '30 4 * * *', env: 'ACCOUNTS_PEOPLE_CHECK_ENABLED',
run: () => require('../accounts/peopleCheck').runPeopleCheck(),
},
{
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old
// passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days.
name: 'accounts-secrets', label: 'Accounts: clear old passwords 14 days after the move, and old sign-in records', cron: '45 3 * * *', env: null,
run: async () => {
const { clearOldSecrets } = require('../accounts/move');
const prisma = require('../config/db');
const old = await prisma.accountsSignIn.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 40 * 24 * 3600e3) } } });
return { ...(await clearOldSecrets(new Date())), signInsRemoved: old.count };
},
},
{
name: 'temp-cleanup', label: 'Delete temp files older than 7 days', cron: '0 3 * * *', env: null,
run: async () => require('../utils/cleanupTemp').cleanupTempFiles(),
@@ -106,13 +125,69 @@ const flag = (name, def = true) => {
return v === undefined || v === '' ? def : String(v).toLowerCase() !== 'false';
};
/** Whether a job is switched on (JOBS_ENABLED and its own flag). */
function isEnabled(job) {
return flag('JOBS_ENABLED') && (!job.env || flag(job.env));
// ─── The admin's choices (3.4.0) ──────────────────────────────────────────────
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30 * 1000;
/** { [job name]: { enabled?: boolean, cron?: string } } from the database, cached here. */
let overrides = {};
let overridesAt = 0;
/** Reads the admin's choices again when the copy here is older than 30 s (or with `force`). */
async function loadOverrides(force = false) {
if (!force && overridesAt && Date.now() - overridesAt < OVERRIDES_TTL_MS) return overrides;
try {
const prisma = require('../config/db');
const row = await prisma.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
overridesAt = Date.now();
} catch (e) {
// Keep the last copy (or none): the .env still applies.
if (force) console.warn('[jobs] Could not read the job overrides:', e?.message || e);
}
return overrides;
}
/** A job's cron schedule, with any JOB_SCHEDULE_<NAME> override (checked). */
/** Sets the cached choices (tests, and after saving). */
function setOverridesForTest(value) {
overrides = value || {};
overridesAt = Date.now();
}
/** A cron expression with five fields that cron-parser understands. */
function isCron(cron) {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
CronExpressionParser.parse(cron, { tz: TIMEZONE });
return true;
} catch {
return false;
}
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
function envEnabled(job) {
return !job.env || flag(job.env);
}
/** Whether a job is switched on: JOBS_ENABLED=false turns all off; then the admin's choice; then its env flag. */
function isEnabled(job) {
if (!flag('JOBS_ENABLED')) return false;
const o = overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** A job's cron schedule: the admin's choice, else JOB_SCHEDULE_<NAME>, else its default. */
function cronFor(job) {
const o = overrides[job.name];
if (o && isCron(o.cron)) return o.cron;
return envCronFor(job);
}
/** A job's cron schedule from the .env (JOB_SCHEDULE_<NAME>, checked), else its default. */
function envCronFor(job) {
const override = process.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (override) {
try {
@@ -197,31 +272,75 @@ const timers = new Map();
// Timer mode keeps its own short history so the admin page still has something to show.
const timerHistory = new Map();
/** One job on an in-process timer while it's on. The schedule and the switch are read each time. */
function startTimer(job) {
const scheduleNext = () => {
if (!isEnabled(job)) { timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(job)).getTime() - Date.now());
timers.set(job.name, setTimeout(async () => {
await loadOverrides();
if (!isEnabled(job)) { timers.delete(job.name); return; }
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: e?.message || String(e) };
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
} finally {
entry.completedOn = new Date();
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
function startTimers(jobs) {
mode = 'timers';
for (const job of jobs) {
const cron = cronFor(job);
const scheduleNext = () => {
const delay = Math.max(1000, nextRun(cron).getTime() - Date.now());
timers.set(job.name, setTimeout(async () => {
const entry = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: e?.message || String(e) };
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
} finally {
entry.completedOn = new Date();
timerHistory.set(job.name, [entry, ...(timerHistory.get(job.name) || [])].slice(0, 10));
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
for (const job of jobs) startTimer(job);
console.log(`[jobs] Running ${jobs.filter(isEnabled).length} job(s) on in-process timers.`);
}
/** Puts one job's schedule in line with its switch and schedule now (queue or timers). */
async function applyJob(job) {
if (mode === 'queue' && boss) {
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
else await boss.unschedule(job.name).catch(() => {});
} else if (mode === 'timers') {
clearTimeout(timers.get(job.name));
timers.delete(job.name);
startTimer(job);
}
console.log(`[jobs] Running ${jobs.length} job(s) on in-process timers.`);
}
const badRequest = (message) => Object.assign(new Error(message), { statusCode: 400 });
/**
* Saves an admin's choice for one job and applies it straight away. `enabled` / `cron`: a value
* wins over the .env; null goes back to the .env; undefined leaves it as it is.
* @returns the job's choices now ({ enabled, cron }, null where the .env applies)
*/
async function setOverride(name, { enabled, cron } = {}) {
const job = JOBS.find(j => j.name === name);
if (!job) throw Object.assign(new Error('Unknown job'), { statusCode: 404 });
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw badRequest('"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim()))) {
throw badRequest('That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const prisma = require('../config/db');
const all = { ...(await loadOverrides(true)) };
const entry = { ...(all[name] || {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = cron.trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await prisma.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
setOverridesForTest(all);
await applyJob(job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/**
@@ -229,12 +348,13 @@ function startTimers(jobs) {
* @returns {Promise<'queue'|'timers'|'off'>}
*/
async function startJobs() {
const enabled = JOBS.filter(isEnabled);
if (!flag('JOBS_ENABLED')) {
console.log('[jobs] All background jobs disabled by env JOBS_ENABLED=false');
mode = 'off';
return mode;
}
await loadOverrides(true);
const enabled = JOBS.filter(isEnabled);
try {
const PgBoss = require('pg-boss');
boss = new PgBoss({ connectionString: process.env.DATABASE_URL, schema: SCHEMA, application_name: 'hope-events-jobs' });
@@ -246,19 +366,21 @@ async function startJobs() {
// stately: at most one waiting and one running, so a slow run never piles up.
await boss.createQueue(job.name, { policy: 'stately', retryLimit: 2, retryDelay: 60, expireInSeconds: 60 * 60 });
}
if (isEnabled(job)) {
await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
await boss.work(job.name, async () => {
try {
return await runJob(job);
} catch (e) {
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
throw e; // recorded as failed, and retried
}
});
} else {
await boss.unschedule(job.name).catch(() => {});
}
// 3.4.0: every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
const list = Array.isArray(batch) ? batch : [batch];
await loadOverrides();
// Switched off (perhaps in another process) after this run was scheduled: skip it. "Run now" still runs.
if (!isEnabled(job) && !list.some(j => j?.data?.manual)) return { skipped: 'switched off' };
try {
return await runJob(job);
} catch (e) {
console.warn(`[jobs] ${job.name} failed:`, e?.message || e);
throw e; // recorded as failed, and retried
}
});
if (isEnabled(job)) await boss.schedule(job.name, cronFor(job), null, { tz: TIMEZONE });
else await boss.unschedule(job.name).catch(() => {});
}
// One-off tasks: any number can wait and run (unlike the stately scheduled jobs).
for (const name of Object.keys(TASKS)) {
@@ -284,7 +406,7 @@ async function startJobs() {
console.warn('[jobs] Job queue unavailable, falling back to timers:', e?.message || e);
if (boss) { try { await boss.stop({ graceful: false }); } catch { /* ignore */ } }
boss = null;
startTimers(enabled);
startTimers(JOBS);
}
return mode;
}
@@ -307,8 +429,9 @@ async function runNow(name) {
err.statusCode = 404;
throw err;
}
if (mode === 'queue' && isEnabled(job)) {
const id = await boss.send(job.name, null, { singletonKey: `${job.name}-manual` });
if (mode === 'queue' && boss) {
// Marked manual so it runs even when the job is switched off.
const id = await boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true, id };
}
const output = await runJob(job);
@@ -319,6 +442,7 @@ async function runNow(name) {
/** Each job with its schedule, next run and recent runs, for the admin page. */
async function jobStatus(prisma) {
await loadOverrides(true);
const recent = new Map();
if (mode === 'queue') {
// pg-boss columns are timestamptz, and Prisma's pg adapter drops their offset in raw queries
@@ -345,11 +469,16 @@ async function jobStatus(prisma) {
return {
mode,
timezone: TIMEZONE,
jobsEnabledEnv: flag('JOBS_ENABLED'),
jobs: JOBS.map(job => {
const cron = cronFor(job);
const enabled = isEnabled(job);
const o = overrides[job.name] || {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
// 3.4.0: what the .env says, and the admin's choice over it (null: the .env applies).
envEnabled: envEnabled(job), envCron: envCronFor(job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron) ? o.cron : null },
nextRun: enabled && mode !== 'off' ? nextRun(cron) : null,
recent: recent.get(job.name) || [],
};
@@ -357,4 +486,7 @@ async function jobStatus(prisma) {
};
}
module.exports = { JOBS, TASKS, TIMEZONE, isEnabled, cronFor, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask };
module.exports = {
JOBS, TASKS, TIMEZONE, isEnabled, envEnabled, cronFor, isCron, nextRun, isNoop, startJobs, stopJobs, runNow, jobStatus, enqueueTask,
setOverride, loadOverrides, setOverridesForTest,
};
+2 -2
View File
@@ -61,7 +61,7 @@ async function firstUse(nonce: string, now: Date): Promise<boolean> {
}
}
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, ip: string | null, metadata: object = {}) {
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string | null; role: string } | null, ip: string | null, metadata: object = {}) {
await logAdminAction({
actorId: actor?.id ?? null,
actorRole: actor?.role ?? 'linked_product',
@@ -80,7 +80,7 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
export async function connectTo(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()) {
export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) {
const sibling = await listedProduct(installId);
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const me = await self();
@@ -2,7 +2,7 @@ const rateLimit = require("express-rate-limit");
const jwt = require('jsonwebtoken');
const prisma = require('../config/db');
const { mustEnrolTwoFactor } = require('../utils/twoFactor');
const { mustEnrolTwoFactor, requiresTwoFactor } = require('../utils/twoFactor');
// The setup wizard's token may finish setup without 2FA for this long.
const SETUP_TOKEN_GRACE_SECONDS = 2 * 60 * 60;
@@ -71,8 +71,14 @@ const protect = async (req, res, next) => {
// requirement (or the user's promotion) is sent back to log in, where they
// enrol. The setup wizard's own token gets a short grace period.
const inSetupGrace = decoded.setup === true && Date.now() / 1000 - (decoded.iat || 0) < SETUP_TOKEN_GRACE_SECONDS;
// 3.0.0: a token from a sign-in through Accounts (`asi`) says whether Accounts asked for the
// second step (`mfa`); Events' own 2FA settings don't apply to it. A token from Events' own
// sign-in (before the move) is checked as before, so nobody is signed out by the move.
const viaAccounts = typeof decoded.asi === 'string';
const needsTwoFactor = viaAccounts ? requiresTwoFactor(req.user) && decoded.mfa !== true : await mustEnrolTwoFactor(req.user);
req.tokenClaims = decoded;
// (An impersonating admin has already passed 2FA themselves.)
if (!inSetupGrace && !req.impersonation && (await mustEnrolTwoFactor(req.user))) {
if (!inSetupGrace && !req.impersonation && needsTwoFactor) {
return res.status(401).json({
message: 'Two-factor authentication is required for your role. Please log in again to set it up.',
code: 'TWO_FACTOR_REQUIRED',
+21
View File
@@ -48,6 +48,13 @@ const frontendUrl = () => (process.env.FRONTEND_URL || process.env.APP_BASE_URL
export async function sendActivationLink(user: { id: string; name?: string | null; email?: string | null; phoneNumber?: string | null }): Promise<void> {
const hasRealEmail = !!(user?.email && !user.email.endsWith('@guest.local'));
if (!hasRealEmail && !user?.phoneNumber) return;
// 3.0.0: once sign-in goes through the church's Accounts, Accounts makes (or finds) their account
// and emails them a link to choose a password; there's no Events activation any more.
if (hasRealEmail && (await (require('../accounts/mode') as typeof import('../accounts/mode')).viaAccounts())) {
ensureAccount(user as { id: string; name?: string | null; email: string; phoneNumber?: string | null })
.catch((e: any) => console.warn('[accounts] Could not make the account:', e?.message || e));
return;
}
try {
const token = uuidv4();
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
@@ -81,6 +88,20 @@ export async function sendActivationLink(user: { id: string; name?: string | nul
}
}
/** Asks Accounts for this person's account (people.ensure) and links it; they can then sign in. */
export async function ensureAccount(user: { id: string; name?: string | null; email: string; phoneNumber?: string | null }): Promise<string | null> {
const { accounts } = require('../accounts/client') as typeof import('../accounts/client');
const { siteUrl } = require('../feed/context') as typeof import('../feed/context');
const { phoneSchema } = require('@crosscode/contracts') as typeof import('@crosscode/contracts');
const phone = user.phoneNumber && phoneSchema.safeParse(user.phoneNumber).success ? user.phoneNumber : null;
const r = await (await accounts()).request<{ sub: string; created: boolean }>({
type: 'people.ensure', actor: null, name: (user.name || user.email).slice(0, 200), email: user.email.toLowerCase(), phone, returnUrl: `${(await siteUrl()).replace(/\/+$/, '')}/`,
});
const other = await prisma.user.findUnique({ where: { accountId: r.sub }, select: { id: true } });
if (!other) await prisma.user.update({ where: { id: user.id }, data: { accountId: r.sub, isActive: true } });
return r.sub;
}
// Fire-and-forget: a login notice with the approximate place it came from.
async function sendLoginNotification(user: any, info: RequestInfo): Promise<void> {
try {
+5 -1
View File
@@ -156,7 +156,10 @@ async function unsubscribe(token, { channels = CHANNELS, source = 'unsubscribe_l
if (target.userId) {
const prefs = {};
for (const c of channels) if (CHANNELS.includes(c)) prefs[c] = false;
return setNewsPreferences(target.userId, prefs, { source, ip });
const state = await setNewsPreferences(target.userId, prefs, { source, ip });
// 3.0.0: off in the church's Accounts too, when sign-in goes through it.
await require('../accounts/news').newsOffInAccounts(target.userId, Object.keys(prefs));
return state;
}
await optOutAddress(target.channel, target.address, { source, ip });
return { optedOut: true };
@@ -281,6 +284,7 @@ async function whatsAppStop(rawPhone) {
const user = await prisma.user.findFirst({ where: { phoneNumber: phone }, select: { id: true } });
if (user) {
await setNewsPreferences(user.id, { whatsapp: false }, { source: 'whatsapp_stop' });
await require('../accounts/news').newsOffInAccounts(user.id, ['whatsapp']);
return 'account';
}
await optOutAddress('whatsapp', phone, { source: 'whatsapp_stop' });
@@ -123,6 +123,9 @@ async function inactiveAccounts(before, { warned, warnedBefore, limit }, db = pr
FROM "User" u
WHERE u."role" = 'user'
AND u."email" NOT LIKE '%@deleted.invalid' AND u."email" NOT LIKE '%@deleted.local'
-- 3.0.0: people who sign in through the church's Accounts are kept or removed there
-- (EVENTS-3.0-PLAN §7); Events still cleans up guests and anyone not linked.
AND u."accountId" IS NULL
) x
WHERE last_active < $1
AND ${warned === false ? '(warned_at IS NULL OR warned_at < last_active)' : 'warned_at >= last_active AND warned_at <= $2'}
+29
View File
@@ -0,0 +1,29 @@
// Where uploaded files live, and how they're served (3.3.0). One folder for saving and serving:
// backend/public/uploads, the same from src/ and dist/. Before 3.3.0 the files were served from
// "public/uploads" relative to wherever the process was started, so a backend started from
// another folder saved a logo in one place and answered 404 for it from another.
const path = require('path');
const express = require('express');
const UPLOADS_DIR = path.join(__dirname, '..', '..', 'public', 'uploads');
/** The folder for one kind of upload (e.g. "branding"), made if it isn't there yet. */
function uploadsDir(sub) {
const dir = path.join(UPLOADS_DIR, sub);
require('fs').mkdirSync(dir, { recursive: true });
return dir;
}
// Uploaded branding assets can include SVGs, which may embed <script>/event handlers. Serving
// them inline lets a malicious upload run script in the site's origin if opened directly, so pin
// the safe response headers (no inline execution, no MIME-sniffing to HTML/script) on every file.
function serveUploads() {
return express.static(UPLOADS_DIR, {
setHeaders: (res) => {
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
res.setHeader('X-Content-Type-Options', 'nosniff');
},
});
}
module.exports = { UPLOADS_DIR, uploadsDir, serveUploads };
+1
View File
@@ -25,6 +25,7 @@ import './resources/auth';
import './resources/ai';
import './resources/feedback';
import './resources/linkedProducts';
import './resources/signIn';
const pkg = require('../../package.json') as { version: string };
@@ -100,7 +100,8 @@ v1Route({ method: 'put', path: '/privacy/breaches/:id', tag: 'Privacy', summary:
// ─── Admin ───────────────────────────────────────────────────────────────────
v1Route({ method: 'get', path: '/admin/audit-log', tag: 'Admin', summary: 'The audit log', access: 'admin', query: filters('page', 'limit', 'actorId', 'action', 'role', 'from', 'to', 'search'), documented: { response: D.obj({ rows: z.array(D.auditEntry), total: D.num, page: D.num, limit: D.num }) }, v1: audit.listAuditLog });
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('on, off or timers'), timezone: D.str, jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('queue, timers or off'), timezone: D.str, jobsEnabledEnv: D.bool.describe('JOBS_ENABLED in the .env'), jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, envEnabled: D.bool.describe('What the .env says'), envCron: D.str, defaultCron: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }).describe('What an admin chose over the .env (null: the .env applies)'), nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs });
v1Route({ method: 'put', path: '/admin/jobs/:name', tag: 'Admin', summary: 'Switch a background job on or off, or change its schedule', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: z.object({ enabled: z.boolean().nullable().optional().describe('true or false wins over the .env; null goes back to it'), cron: z.string().max(100).nullable().optional().describe('A cron schedule (five fields) that wins over the .env; null or empty goes back to it') }), documented: { response: D.obj({ name: D.str, override: D.obj({ enabled: z.boolean().nullable(), cron: D.optStr }) }) }, v1: jobs.updateJob });
v1Route({ method: 'post', path: '/admin/jobs/:name/run', tag: 'Admin', summary: 'Run a background job now', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: loose, documented: { response: D.obj({ queued: D.bool, id: D.optStr, output: z.unknown().optional().describe('When it ran straight away') }) }, v1: jobs.runJobNow });
v1Route({ method: 'get', path: '/admin/impersonation-sessions', tag: 'Admin', summary: 'Times admins viewed the site as someone else', access: 'admin', query: filters('limit'), documented: { response: z.array(D.obj({ id: D.str, reason: D.optStr, startedAt: D.optDate, endedAt: D.optDate, expiresAt: D.optDate, admin: D.obj({ name: D.str, email: D.optStr }).nullish(), target: D.obj({ name: D.str, email: D.optStr }).nullish(), requests: z.array(D.obj({ method: D.str, path: D.str, blocked: D.bool, createdAt: D.date })).describe('What they did (up to 500)') })) }, v1: imp.listSessions });
v1Route({ method: 'post', path: '/admin/impersonate/:userId', tag: 'Admin', summary: 'View the site as someone (read-only)', description: 'Answers a token for a read-only session, logged.', access: 'admin', params: z.object({ userId: z.string().min(1).max(64) }), body: loose, documented: { body: D.obj({ reason: D.str.describe('Why — kept in the log') }), response: D.obj({ token: D.str.describe('A read-only sign-in token'), session: D.obj({ id: D.str, expiresAt: D.date, target: D.obj({ id: D.str, name: D.str, email: D.str, role: D.str }) }) }) }, v1: imp.startImpersonation });
@@ -0,0 +1,314 @@
import { z } from 'zod';
import { defineRoute } from '../route';
import { ApiError, notFound } from '../errors';
import { single } from '../paging';
import { authMode } from '../../accounts/mode';
import { check, move, MoveError, status, undo } from '../../accounts/move';
import { accounts, accountsLink, AccountsUnavailable } from '../../accounts/client';
import { accountsMessaging, eventsMessaging, sendToAccounts } from '../../accounts/messaging';
import { churchLook } from '../../accounts/look';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../../config/db');
const { logAdminAction } = require('../../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
/**
* Settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, the move to the
* church's Accounts (check, move, undo), and what an admin can do to someone's account from here
* once sign-in goes through Accounts (§6). And, for every page, where to send someone to sign in.
*/
function asApiError(e: unknown): never {
if (e instanceof MoveError) {
const code = e.status === 503 || e.status === 502 ? 'UNAVAILABLE' : 'CONFLICT';
throw new ApiError(code, e.message);
}
if (e instanceof AccountsUnavailable) throw new ApiError('UNAVAILABLE', e.message);
const err = e as { code?: string; message?: string; status?: number };
if (err?.code && typeof err.status === 'number') {
if (err.code === 'UNKNOWN_PERSON') throw new ApiError('NOT_FOUND', 'Accounts doesn\'t know this person through Cross Events yet. They need to sign in once first.');
if (err.code === 'NOT_ALLOWED') throw new ApiError('FORBIDDEN', err.message ?? 'Accounts didn\'t allow that.');
throw new ApiError('UNAVAILABLE', `Accounts didn't accept that: ${err.message}`);
}
throw e;
}
const person = z.object({ name: z.string(), email: z.string() });
const statusSchema = z.object({
mode: z.enum(['local', 'accounts']).describe('local: Cross Events\' own sign-in; accounts: through the church\'s Accounts'),
accountsConnected: z.boolean(),
accountsUrl: z.string().nullable(),
movedAt: z.string().nullable(),
undoUntil: z.string().nullable().describe('Undo is possible until then (14 days after the move)'),
secretsCleared: z.boolean().describe('The old passwords have been removed (Undo is no longer possible)'),
running: z.boolean(),
report: z.unknown().nullable(),
});
export const signInMode = defineRoute({
method: 'get',
path: '/auth/mode',
tag: 'Accounts',
summary: 'Where people sign in',
description: '`accounts`: send people to `GET /api/auth/signin?returnTo=<this page>` (the church\'s Accounts). `local`: Cross Events\' own sign-in.',
access: 'public',
response: single(z.object({
mode: z.enum(['local', 'accounts']),
signInUrl: z.string(),
accountUrl: z.string().nullable().describe('With `accounts`: the church account page (profile, password, two-step sign-in, privacy)'),
})),
async handler() {
const mode = await authMode();
const link = mode === 'accounts' ? await accountsLink() : null;
return { data: { mode, signInUrl: '/api/auth/signin', accountUrl: link ? `${link.url.replace(/\/+$/, '')}/api/self/signin?returnTo=/account` : null } };
},
});
export const signInStatus = defineRoute({
method: 'get',
path: '/settings/sign-in',
tag: 'Accounts',
summary: 'Sign-in: where it is and the move to Accounts',
access: 'admin',
response: single(statusSchema),
async handler() {
return { data: await status() };
},
});
export const signInCheck = defineRoute({
method: 'post',
path: '/settings/sign-in/check',
tag: 'Accounts',
summary: 'Check the move to Accounts (nothing changes)',
description: 'Who would move, who already has an account (they\'re linked to it), who is skipped (guests, deleted) and anything that would stop the move.',
access: 'admin',
response: single(z.object({
accountsVersion: z.string(),
toMove: z.number().int(),
wouldCreate: z.number().int(),
wouldLink: z.array(person),
refused: z.array(person.extend({ reason: z.string() })),
skipped: z.number().int(),
admins: z.array(person.extend({ id: z.string() })),
noticeConflict: z.object({ accountsVersions: z.array(z.number()), eventsVersions: z.array(z.number()) }).nullable(),
withTwoFactor: z.number().int(),
messaging: z.object({ email: z.boolean(), whatsapp: z.boolean(), whatsappTwoFactor: z.number().int() }).describe('3.1.0: what Accounts can send; the move needs email'),
})),
async handler() {
return { data: await check().catch(asApiError) };
},
});
export const signInMove = defineRoute({
method: 'post',
path: '/settings/sign-in/move',
tag: 'Accounts',
summary: 'Move sign-in to Accounts',
description: 'Copies everyone into the church\'s Accounts with their passwords and authenticator apps, checks the count, then switches. Nothing switches if anything fails, and it can be run again. Undo for 14 days.',
access: 'admin',
body: z.object({
adminIds: z.array(z.uuid()).max(500).describe('Events admins who also become Accounts admins'),
keepAccountsNotices: z.boolean().optional().describe('When Accounts has its own privacy notice: keep it (everyone accepts it at their next sign-in) instead of Events\''),
}),
response: single(statusSchema),
async handler({ body, user, req }) {
const me = await prisma.user.findUnique({ where: { id: user!.id }, select: { name: true } });
await move({ actor: { id: user!.id, role: user!.role, name: me?.name }, adminIds: body.adminIds, keepAccountsNotices: body.keepAccountsNotices, ip: getClientIp(req) }).catch(asApiError);
return { data: await status() };
},
});
export const signInUndo = defineRoute({
method: 'post',
path: '/settings/sign-in/undo',
tag: 'Accounts',
summary: 'Undo the move (back to Cross Events\' own sign-in)',
description: 'Within 14 days of the move. People sign in with the password they had at the move; changes made in Accounts since then don\'t come back here.',
access: 'admin',
response: single(statusSchema),
async handler({ user, req }) {
return { data: await undo({ id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError) };
},
});
// ─── Email and WhatsApp for Accounts (3.1.0) ────────────────────────────────
const messagingOverview = z.object({
events: z.object({
email: z.object({ host: z.string(), port: z.number().int(), secure: z.boolean(), user: z.string(), from: z.string(), hasPass: z.boolean() }).nullable(),
whatsapp: z.object({ instanceId: z.string(), hasToken: z.boolean() }).nullable(),
}).describe("This site's own settings, to copy (never the password or token)"),
accounts: z.object({
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
}).nullable().describe("What the church's Accounts can send (null: it can't be reached)"),
accountsError: z.string().nullable(),
});
export const signInMessaging = defineRoute({
method: 'get',
path: '/settings/sign-in/messaging',
tag: 'Accounts',
summary: "Email and WhatsApp: this site's, and what Accounts can send",
access: 'admin',
response: single(messagingOverview),
async handler() {
const events = await eventsMessaging();
try {
return { data: { events, accounts: await accountsMessaging(), accountsError: null } };
} catch (e) {
return { data: { events, accounts: null, accountsError: (e as Error).message } };
}
},
});
/** 082 123 4567 → +27821234567 (as Accounts keeps phone numbers). */
const toE164 = (raw: string) => {
const d = raw.replace(/\D/g, '');
if (raw.trim().startsWith('+')) return `+${d}`;
return d.startsWith('0') && d.length === 10 ? `+27${d.slice(1)}` : `+${d}`;
};
const messagingBody = z.object({
email: z.object({
host: z.string().trim().min(1).max(253),
port: z.number().int().min(1).max(65535),
secure: z.boolean(),
user: z.string().max(254),
from: z.string().trim().min(3).max(320),
pass: z.string().max(500).nullable().optional().describe("Blank: this site's own password"),
to: z.email().describe('Where the test email goes'),
}).optional(),
whatsapp: z.object({
instanceId: z.string().trim().min(1).max(200),
accessToken: z.string().max(500).nullable().optional().describe("Blank: this site's own token"),
to: z.string().trim().min(8).max(30).describe('The phone the test message goes to'),
}).optional(),
});
const messagingResult = z.object({ ok: z.boolean(), error: z.string().nullable(), saved: z.boolean() }).nullable();
const messagingAnswer = single(z.object({ email: messagingResult, whatsapp: messagingResult, status: z.object({ email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }), whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }) }) }));
async function messagingFor(body: z.infer<typeof messagingBody>, user: { id: string; role: string }, req: unknown, save: boolean) {
if (!body.email && !body.whatsapp) throw new ApiError('VALIDATION_FAILED', 'Give email or WhatsApp settings.');
const actor = (await prisma.user.findUnique({ where: { id: user.id }, select: { accountId: true } }))?.accountId ?? null;
const input = { ...(body.email ? { email: body.email } : {}), ...(body.whatsapp ? { whatsapp: { ...body.whatsapp, to: toE164(body.whatsapp.to) } } : {}) };
const out = await sendToAccounts(input, { save, actor }).catch(asApiError);
if (save) {
await logAdminAction({ actorId: user.id, actorRole: user.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_messaging', metadata: { email: out.email && { ok: out.email.ok, saved: out.email.saved, host: body.email?.host }, whatsapp: out.whatsapp && { ok: out.whatsapp.ok, saved: out.whatsapp.saved } }, ip: getClientIp(req) });
}
return { data: out };
}
export const signInMessagingTest = defineRoute({
method: 'post',
path: '/settings/sign-in/messaging/test',
tag: 'Accounts',
summary: 'Test email / WhatsApp settings through Accounts (nothing saved)',
description: "Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.",
access: 'admin',
body: messagingBody,
response: messagingAnswer,
async handler({ body, user, req }) {
return messagingFor(body, user!, req, false);
},
});
export const signInMessagingSave = defineRoute({
method: 'post',
path: '/settings/sign-in/messaging',
tag: 'Accounts',
summary: 'Save email / WhatsApp settings in Accounts (after a test)',
description: 'Accounts tests each part as /test does, and saves it only if its test worked.',
access: 'admin',
body: messagingBody,
response: messagingAnswer,
async handler({ body, user, req }) {
return messagingFor(body, user!, req, true);
},
});
export const signInLook = defineRoute({
method: 'post',
path: '/settings/sign-in/look',
tag: 'Accounts',
summary: "Use this site's logo and colours on the church's sign-in pages",
description: "Sends this site's name, logo and colours to the church's Accounts, replacing what its sign-in pages had.",
access: 'admin',
response: single(z.object({ name: z.string().nullable(), logoUrl: z.string().nullable(), primaryColour: z.string().nullable(), accentColour: z.string().nullable() })),
async handler({ user, req }) {
const look = await churchLook();
const actor = (await prisma.user.findUnique({ where: { id: user!.id }, select: { accountId: true } }))?.accountId ?? null;
await (await accounts().catch(asApiError)).request({ type: 'church.branding', actor, church: look, overwrite: true }).catch(asApiError);
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_look', metadata: look, ip: getClientIp(req) });
return { data: { name: look.name, logoUrl: look.logoUrl ?? null, primaryColour: look.primaryColour, accentColour: look.accentColour ?? null } };
},
});
// ─── An admin, for someone's account (sign-in through Accounts) ─────────────
const idParams = z.object({ id: z.uuid() });
async function targetFor(id: string) {
const u = await prisma.user.findUnique({ where: { id }, select: { id: true, accountId: true, name: true } });
if (!u) throw notFound('That person');
if (!u.accountId) throw new ApiError('CONFLICT', `${u.name} doesn't sign in through the church's account yet.`);
return u as { id: string; accountId: string; name: string };
}
async function forAccount(id: string, admin: { id: string; role: string }, req: unknown, what: 'people.resetTwoFactor' | 'people.unlock' | 'people.setActive', extra: object = {}) {
if ((await authMode()) !== 'accounts') throw new ApiError('CONFLICT', 'Sign-in is still in Cross Events: use the account\'s own settings here.');
const target = await targetFor(id);
const actor = (await prisma.user.findUnique({ where: { id: admin.id }, select: { accountId: true } }))?.accountId ?? null;
await (await accounts().catch(asApiError)).request({ type: what, actor, sub: target.accountId, ...extra } as never).catch(asApiError);
await logAdminAction({ actorId: admin.id, actorRole: admin.role, action: 'account_changed_in_accounts', targetType: 'user', targetId: target.id, metadata: { request: what, ...extra }, ip: getClientIp(req) });
return { data: { ok: true as const } };
}
const ok = single(z.object({ ok: z.literal(true) }));
export const accountResetTwoFactor = defineRoute({
method: 'post',
path: '/users/:id/account/reset-two-factor',
tag: 'Accounts',
summary: 'Reset someone\'s two-step sign-in (in Accounts)',
description: 'They set it up again at their next sign-in, and are signed out everywhere.',
access: 'admin',
params: idParams,
response: ok,
async handler({ params, user, req }) {
return forAccount(params.id, user!, req, 'people.resetTwoFactor');
},
});
export const accountUnlock = defineRoute({
method: 'post',
path: '/users/:id/account/unlock',
tag: 'Accounts',
summary: 'Unlock someone after too many wrong passwords (in Accounts)',
access: 'admin',
params: idParams,
response: ok,
async handler({ params, user, req }) {
return forAccount(params.id, user!, req, 'people.unlock');
},
});
export const accountSetActive = defineRoute({
method: 'post',
path: '/users/:id/account/active',
tag: 'Accounts',
summary: 'Turn someone\'s church account off or on everywhere (in Accounts)',
description: 'Off signs them out of every product of the church. To only stop them using Cross Events, deactivate them here instead.',
access: 'admin',
params: idParams,
body: z.object({ active: z.boolean() }),
response: ok,
async handler({ params, body, user, req }) {
return forAccount(params.id, user!, req, 'people.setActive', { active: body.active });
},
});
@@ -0,0 +1,313 @@
// Cross Events 3.0 against the real Accounts (docs/EVENTS-3.0-PLAN.md §12): Events' own code (the
// move, sign-in, sign-out, Accounts' calls) talking to the whole Accounts app on real ports, each with
// an in-memory database. Run with `npm run test:accounts` (node:test through tsx, not Jest: Accounts
// is ES modules).
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { createRequire } from 'node:module';
import { after, before, describe, test } from 'node:test';
import bcrypt from 'bcryptjs';
import express from 'express';
import jwt from 'jsonwebtoken';
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
import { Browser, startHarness, ACCOUNTS_ID, type Harness } from '../../../../accounts/backend/tests/support/harness.ts';
import { memoryDb } from '../../../../accounts/backend/tests/support/memoryDb.ts';
import { codeAt, generateSecret } from '../../../../accounts/backend/src/lib/totp.ts';
import { runDue } from '../../../../accounts/backend/src/links/deliveries.ts';
import { signOutEverywhere } from '../../../../accounts/backend/src/oidc/sessions.ts';
import { profileChanged } from '../../../../accounts/backend/src/accounts/service.ts';
const require = createRequire(import.meta.url);
process.env.NODE_ENV = 'test';
process.env.JWT_SECRET = 'an-events-test-secret-long-enough-for-the-encryption-key';
// With EVENTS_TEST_DATABASE_URL and ACCOUNTS_TEST_DATABASE_URL (empty, migrated databases), both
// apps use real Postgres; otherwise in-memory stand-ins (Events' with Prisma's `{ increment }`).
const PG = !!(process.env.EVENTS_TEST_DATABASE_URL && process.env.ACCOUNTS_TEST_DATABASE_URL);
if (PG) process.env.DATABASE_URL = process.env.EVENTS_TEST_DATABASE_URL;
const raw = memoryDb();
const eventsDb = new Proxy(raw, {
get(target, prop: string) {
const model = (target as unknown as Record<string, Record<string, (...a: unknown[]) => Promise<unknown>>>)[prop];
if (prop !== 'user') return model;
return new Proxy(model, {
get(m, op: string) {
if (op !== 'update') return m[op];
return async (args: { where: Record<string, unknown>; data: Record<string, unknown>; select?: Record<string, boolean> }) => {
const inc = args.data.tokenVersion as { increment?: number } | undefined;
if (inc && typeof inc === 'object' && 'increment' in inc) {
const cur = (await m.findUnique!({ where: args.where })) as { tokenVersion: number };
args = { ...args, data: { ...args.data, tokenVersion: cur.tokenVersion + inc.increment! } };
}
return m.update!(args);
};
},
});
},
});
const dbPath = require.resolve('../../src/config/db.js');
if (!PG) require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: eventsDb } as never;
const realEventsDb = PG ? require(dbPath) : null;
const edb = (realEventsDb ?? eventsDb) as typeof eventsDb;
const { encrypt } = require('../../src/utils/encryption.js');
const { accountsRouter } = require('../../src/accounts/signin.ts');
const { signInGuard } = require('../../src/accounts/guard.ts');
const { protect } = require('../../src/middleware/authMiddleware.js');
const move = require('../../src/accounts/move.ts');
const mode = require('../../src/accounts/mode.ts');
const messaging = require('../../src/accounts/messaging.ts');
const { setAuthClientLoader } = require('../../src/accounts/client.ts');
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
let h: Harness;
let eventsUrl: string;
let server: http.Server;
const totpSecret = generateSecret();
const ids = { thandi: crypto.randomUUID(), sam: crypto.randomUUID(), lerato: crypto.randomUUID(), guest: crypto.randomUUID(), sipho: crypto.randomUUID() };
async function eventsUser(data: Record<string, unknown>) {
return edb.user.create({
data: {
accountId: null, role: 'user', isActive: true, tokenVersion: 0, phoneNumber: null, failedAttempts: 0, lockUntil: null, twoFactorEnabled: false, twoFactorMethod: null,
totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: new Date(), noticeVersionAccepted: 0, lastLoginAt: new Date('2026-10-01'),
notificationPreference: 'email', inactivityWarnedAt: null, ...data,
},
});
}
before(async () => {
if (PG) {
const { PrismaClient } = await import('../../../../accounts/backend/src/generated/prisma/client.ts');
const { PrismaPg } = await import('@prisma/adapter-pg');
h = await startHarness({ db: new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.ACCOUNTS_TEST_DATABASE_URL! }) }) });
} else {
h = await startHarness();
}
setAuthClientLoader(() => import('@crosscode/auth-client'));
// Events on a real port: the sign-in routes, the guard, and one page that needs signing in.
const app = express();
app.use('/api', accountsRouter(protect));
app.use(express.json());
app.use((req, res, next) => { signInGuard(req, res, next).catch(next); });
app.get('/api/v2/me', protect, (req, res) => res.json({ data: { id: (req as unknown as { user: { id: string } }).user.id } }));
app.post('/api/v2/auth/login', (_req, res) => res.json({ data: { status: 'local' } }));
server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
eventsUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
process.env.FRONTEND_URL = eventsUrl;
// Connect (as Linked products would): the same secret on both sides.
const secret = newLinkSecret();
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: eventsUrl, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
await edb.productLink.create({ data: { installId: ACCOUNTS_ID, product: 'accounts', url: h.publicUrl, publicKey: 'x', secret: encrypt(secret), connectedAt: new Date(), updatedAt: new Date() } });
await edb.appSetting.create({ data: { key: 'hub_install_id', value: EVENTS_ID } });
// This site's own email settings (3.1.0: copied to Accounts before the move).
for (const [key, value] of Object.entries({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_secure: 'false', smtp_user: 'events@hope.test', smtp_pass: 'events-mail-pass', smtp_from: 'events@hope.test' })) {
await edb.appSetting.create({ data: { key, value } });
}
// Events' people before the move.
await eventsUser({ id: ids.thandi, name: 'Thandi Mokoena', email: 'thandi@hope.test', password: await bcrypt.hash('Old-events-pass1', 4), newsEmail: true });
await eventsUser({ id: ids.sam, name: 'Sam Admin', email: 'sam@hope.test', role: 'admin', password: await bcrypt.hash('Admin-pass-123', 4), twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: encrypt(totpSecret), totpLastStep: 1 });
await eventsUser({ id: ids.lerato, name: 'Lerato', email: 'lerato@hope.test', password: await bcrypt.hash('Events-pass-99', 4) });
await eventsUser({ id: ids.sipho, name: 'Sipho Supervisor', email: 'sipho@hope.test', role: 'supervisor', password: await bcrypt.hash('Sipho-pass-123', 4) });
await eventsUser({ id: ids.guest, name: 'Door Guest', email: 'guest+ab12cd34@guest.local', password: 'x' });
// Lerato already made a church account (e.g. on the website) with another password.
await h.makeAccount({ email: 'lerato@hope.test', password: 'Accounts-pass-1', name: 'Lerato M' });
});
after(async () => {
await new Promise((r) => server.close(r));
await h.close();
});
/** Signs in through Events: Events → Accounts → Events' callback → /auth/complete#code → handoff. */
async function signInThroughEvents(browser: Browser, email: string, password: string, returnTo: string, opts: { totp?: string } = {}) {
const start = `${eventsUrl}/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}`;
const toComplete = (u: URL) => u.host === new URL(eventsUrl).host && (u.pathname === '/auth/complete' || u.pathname === '/auth/problem');
let at = await browser.follow(start, (u) => u.pathname === '/signin' || toComplete(u));
const steps: Record<string, unknown>[] = [];
for (let i = 0; i < 4 && at.url.pathname === '/signin'; i++) {
const uid = at.url.searchParams.get('uid')!;
let step = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
if (step.body.stage === 'password') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
if (step.body.stage === 'two_factor') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor`, { code: codeAt(opts.totp!, Math.floor(Date.now() / 30000)) });
steps.push(step.body);
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || toComplete(u));
}
if (at.url.pathname === '/auth/problem') return { problem: at.url.searchParams.get('code'), steps };
const code = at.url.hash.slice(1);
const res = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }) });
const body = (await res.json()) as { data: { token: string; returnTo: string; user: { id: string } } };
return { ...body.data, code, steps };
}
const me = (token: string) => fetch(`${eventsUrl}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } });
describe('Accounts\' email before the move (3.1.0)', () => {
test('without email in Accounts, the check says so and the move is refused', async () => {
(h.messenger as unknown as { emailOn: boolean }).emailOn = false;
const r = await move.check();
assert.equal(r.messaging.email, false);
await assert.rejects(move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] }), (e: { code?: string }) => e.code === 'EMAIL_NOT_READY');
mode.forgetMode();
assert.equal(await mode.authMode(), 'local');
});
test('this site\'s SMTP is copied (its own password, never sent to the page), tested, then saved in Accounts', async () => {
const own = await messaging.eventsMessaging();
assert.deepEqual(own.email, { host: 'smtp.hope.test', port: 587, secure: false, user: 'events@hope.test', from: 'events@hope.test', hasPass: true });
const email = { host: own.email.host, port: own.email.port, secure: own.email.secure, user: own.email.user, from: own.email.from, pass: null, to: 'sam@hope.test' };
const tested = await messaging.sendToAccounts({ email }, { save: false, actor: null });
assert.deepEqual(tested.email, { ok: true, error: null, saved: false });
const tried = (h.messenger as unknown as { tried: { settings: { pass: string } }[] }).tried.at(-1)!;
assert.equal(tried.settings.pass, 'events-mail-pass', 'this site\'s own password, sealed on the way');
assert.equal(await h.ctx.settings.get('smtp_host'), null, 'a test saves nothing');
const saved = await messaging.sendToAccounts({ email }, { save: true, actor: null });
assert.equal(saved.email.saved, true);
assert.equal(await h.ctx.settings.get('smtp_pass'), 'events-mail-pass');
// (The in-memory messenger stands for a working SMTP from here.)
(h.messenger as unknown as { emailOn: boolean }).emailOn = true;
assert.equal((await messaging.accountsMessaging()).email.ready, true);
});
});
describe('moving Events\' sign-in to Accounts', () => {
test('the check counts people and writes nothing', async () => {
const r = await move.check();
assert.equal(r.toMove, 4, 'the guest stays');
assert.equal(r.skipped, 1);
assert.equal(r.wouldCreate, 3);
assert.deepEqual(r.wouldLink.map((l: { email: string }) => l.email), ['lerato@hope.test']);
assert.deepEqual(r.admins.map((a: { id: string }) => a.id), [ids.sam]);
assert.equal(await h.db.account.findUnique({ where: { id: ids.thandi } }), null);
assert.equal(await mode.authMode(), 'local');
});
test('the move copies everyone, links Lerato to her account, and switches', async () => {
const report = await move.move({ actor: { id: ids.sam, role: 'admin', name: 'Sam Admin' }, adminIds: [ids.sam] });
assert.equal(report.created, 3);
assert.equal(report.linked.length, 1);
mode.forgetMode();
assert.equal(await mode.authMode(), 'accounts');
const thandi = await edb.user.findUnique({ where: { id: ids.thandi } }) as { accountId: string };
assert.equal(thandi.accountId, ids.thandi, 'sub = Events id');
const lerato = await edb.user.findUnique({ where: { id: ids.lerato } }) as { accountId: string };
const account = await h.db.account.findUnique({ where: { email: 'lerato@hope.test' } }) as { id: string };
assert.equal(lerato.accountId, account.id, 'linked to the account she had');
assert.equal((await edb.user.findUnique({ where: { id: ids.guest } }) as { accountId: string | null }).accountId, null);
assert.equal((await h.db.account.findUnique({ where: { id: ids.sam } }) as { role: string }).role, 'admin');
});
});
describe('signing in through Events after the move', () => {
test('Thandi signs in with her old Events password and lands on the page she started from', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/events/youth-camp/register?ticket=adult');
assert.ok('token' in r && r.token, JSON.stringify(r));
assert.equal(r.returnTo, '/events/youth-camp/register?ticket=adult');
assert.equal(r.user.id, ids.thandi);
assert.equal((await me(r.token)).status, 200);
// The code is single use.
const again = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: r.code }) });
assert.equal(again.status, 400);
});
test('a foreign return address lands on the home page instead', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '//evil.test/steal');
assert.ok('returnTo' in r);
assert.equal(r.returnTo, '/');
});
test('the admin signs in with the old authenticator app, gets new recovery codes, and the token says mfa', async () => {
const r = await signInThroughEvents(new Browser(), 'sam@hope.test', 'Admin-pass-123', '/dashboard/admin', { totp: totpSecret });
assert.ok('token' in r && r.token, JSON.stringify(r));
assert.equal((r.steps[0]!.recoveryCodes as string[]).length, 10);
assert.equal((jwt.decode(r.token) as { mfa: boolean }).mfa, true);
assert.equal((await me(r.token)).status, 200);
});
test('a supervisor without 2FA is sent back to Accounts to set it up', async () => {
const browser = new Browser();
const start = `${eventsUrl}/api/auth/signin?returnTo=/dashboard`;
let at = await browser.follow(start, (u) => u.pathname === '/signin');
const uid = at.url.searchParams.get('uid')!;
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'sipho@hope.test', password: 'Sipho-pass-123' });
assert.equal(step.body.stage, 'done');
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || u.pathname === '/auth/complete');
assert.equal(at.url.pathname, '/signin', 'back at Accounts for the second step');
const state = await h.api(browser, 'GET', `/api/v2/interaction/${at.url.searchParams.get('uid')}/state`);
assert.equal(state.body.stage, 'setup_two_factor');
});
test('Events\' own sign-in now says where to go', async () => {
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
assert.equal(res.status, 409);
assert.equal(((await res.json()) as { error: { code: string } }).error.code, 'SIGN_IN_MOVED');
});
});
describe('signing out, and Accounts\' calls', () => {
test('signing out of Events ends the session here and gives Accounts\' sign-out address', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
assert.ok('token' in r);
const out = await fetch(`${eventsUrl}/api/auth/signout`, { method: 'POST', headers: { authorization: `Bearer ${r.token}`, 'content-type': 'application/json' }, body: '{}' });
const body = (await out.json()) as { data: { url: string } };
assert.match(body.data.url, new RegExp(`^${h.publicUrl}/api/oidc/session/end`));
assert.equal((await me(r.token)).status, 401);
});
test('signing out everywhere in Accounts ends the Events session (back-channel logout)', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
assert.ok('token' in r);
assert.equal((await me(r.token)).status, 200);
await signOutEverywhere(h.ctx, h.provider, ids.thandi);
assert.equal((await me(r.token)).status, 401);
});
test('a name changed in Accounts reaches Events (user.updated)', async () => {
await h.db.account.update({ where: { id: ids.thandi }, data: { name: 'Thandi M. Mokoena' } });
await profileChanged(h.ctx, ids.thandi);
await runDue(h.ctx);
assert.equal((await edb.user.findUnique({ where: { id: ids.thandi } }) as { name: string }).name, 'Thandi M. Mokoena');
});
test('people added here after the move (demo data) are moved too, and can sign in', async () => {
const id = crypto.randomUUID();
await eventsUser({ id, name: 'Demo Person', email: 'demo.person@hope.test', password: await bcrypt.hash('Demo-pass-123', 4) });
const r = await move.moveNewPeople(null);
assert.equal(r.moved, 1);
assert.equal((await edb.user.findUnique({ where: { id } }) as { accountId: string }).accountId, id);
const signed = await signInThroughEvents(new Browser(), 'demo.person@hope.test', 'Demo-pass-123', '/');
assert.ok('token' in signed && signed.token);
});
test('someone new to Events signs in with a church account they made elsewhere', async () => {
const a = await h.makeAccount({ email: 'newcomer@hope.test', password: 'Newcomer-pass-1', name: 'Newcomer' });
const r = await signInThroughEvents(new Browser(), 'newcomer@hope.test', 'Newcomer-pass-1', '/events');
assert.ok('token' in r && r.token, JSON.stringify(r));
assert.equal((await edb.user.findUnique({ where: { id: r.user.id } }) as { accountId: string; role: string }).accountId, a.id);
});
test('Undo goes back to Events\' own sign-in', async () => {
await move.undo({ id: ids.sam, role: 'admin' });
mode.forgetMode();
assert.equal(await mode.authMode(), 'local');
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
assert.equal(res.status, 200);
});
});
describe('moving again after Undo', () => {
test('works, including someone who joined through Accounts in between', async () => {
mode.forgetMode();
assert.equal(await mode.authMode(), 'local');
const report = await move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] });
assert.equal(report.created, 0, 'nobody new to move');
mode.forgetMode();
assert.equal(await mode.authMode(), 'accounts');
});
});
@@ -0,0 +1,61 @@
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §9): connecting to the church's Accounts once the Hub lists it.
const mockSettings = new Map<string, string>();
const mockConnects: unknown[][] = [];
let mockListed: { installId: string; product: string }[] = [];
let mockLink: object | null = null;
jest.mock('../src/links/connect', () => ({ connectTo: async (...args: unknown[]) => { mockConnects.push(args); mockLink = { installId: args[0] }; } }));
jest.mock('../src/links/store', () => ({ linkedProducts: async () => mockListed }));
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
let mockMode = 'local';
jest.mock('../src/accounts/mode', () => ({
viaAccounts: async () => mockMode === 'accounts',
getSetting: async (k: string) => mockSettings.get(k) ?? null,
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
}));
import { AUTO_KEY, connectAccountsIfListed } from '../src/accounts/autoConnect';
const ACCOUNTS = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
beforeEach(() => {
mockSettings.clear();
mockConnects.length = 0;
mockListed = [];
mockLink = null;
mockMode = 'local';
});
test('connects to the Accounts the Hub lists, as the system, once', async () => {
mockListed = [{ installId: 'w1', product: 'website' }, { installId: ACCOUNTS, product: 'accounts' }];
expect(await connectAccountsIfListed()).toBe('connected');
expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]);
expect(mockSettings.has(AUTO_KEY)).toBe(true);
// An admin disconnects later: it isn't connected again.
mockLink = null;
expect(await connectAccountsIfListed()).toBe('skipped');
expect(mockConnects).toHaveLength(1);
});
test('nothing listed yet: tries again at the next heartbeat', async () => {
expect(await connectAccountsIfListed()).toBe('skipped');
expect(mockSettings.has(AUTO_KEY)).toBe(false);
});
test('already connected by an admin: just remembers it', async () => {
mockLink = { installId: ACCOUNTS };
mockListed = [{ installId: ACCOUNTS, product: 'accounts' }];
expect(await connectAccountsIfListed()).toBe('skipped');
expect(mockConnects).toEqual([]);
expect(mockSettings.has(AUTO_KEY)).toBe(true);
});
test('3.5.0: a site in Accounts mode that lost its link (a demo load before 3.5.0) connects again', async () => {
mockSettings.set(AUTO_KEY, '2026-11-19T10:00:00.000Z');
mockListed = [{ installId: ACCOUNTS, product: 'accounts' }];
// On its own sign-in, an earlier Disconnect stays.
expect(await connectAccountsIfListed()).toBe('skipped');
mockMode = 'accounts';
expect(await connectAccountsIfListed()).toBe('connected');
expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]);
});
@@ -0,0 +1,71 @@
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §7): Accounts' user.export and user.deleted calls, answered with
// Events' existing export and deletion rules. The sign-in itself, the move and the other calls run
// against the real Accounts in tests/accounts-integration (npm run test:accounts).
const mockUsers = new Map<string, { id: string; accountId: string | null; tokenVersion: number }>();
const mockAnonymised: string[] = [];
let mockBlockers: { eventTitle: string; endDate: Date }[] = [];
jest.mock('../src/config/db', () => ({
user: {
findUnique: async ({ where }: { where: { accountId?: string; id?: string } }) =>
[...mockUsers.values()].find((u) => (where.accountId ? u.accountId === where.accountId : u.id === where.id)) ?? null,
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {
const u = mockUsers.get(where.id)!;
if (data.tokenVersion && typeof data.tokenVersion === 'object') u.tokenVersion += 1;
if ('accountId' in data) u.accountId = data.accountId as string | null;
return u;
},
},
}));
jest.mock('../src/utils/privacy', () => ({
exportUserData: async (id: string) => ({ account: { id, name: 'Thandi' }, registrations: [{ event: 'Youth Camp' }], payments: [], seasonPasses: [] }),
deletionBlockers: async () => mockBlockers,
anonymiseUser: async (id: string) => { mockAnonymised.push(id); },
}));
import { IDENTITY_SCHEMA, userDeletedReplySchema, userExportReplySchema } from '@crosscode/contracts';
import { exportSections, handleAccountsCall } from '../src/accounts/calls';
const SUB = '5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90';
const base = { schema: IDENTITY_SCHEMA, callId: '0b6e1f2a-3c4d-4e5f-8a9b-0c1d2e3f4a5b', occurredAt: '2026-11-20T10:00:00.000Z', sub: SUB } as const;
beforeEach(() => {
mockUsers.clear();
mockUsers.set('u1', { id: 'u1', accountId: SUB, tokenVersion: 0 });
mockAnonymised.length = 0;
mockBlockers = [];
});
test('user.export answers with Events\' export as sections, empty ones left out', async () => {
const reply = await handleAccountsCall({ ...base, type: 'user.export', exportId: '1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c' });
expect(userExportReplySchema.safeParse(reply).success).toBe(true);
const sections = (reply as { sections: { key: string; title: string }[] }).sections;
expect(sections.map((s) => s.key)).toEqual(['account', 'registrations']);
expect(sections[1]!.title).toBe('Registrations');
});
test('section keys fit the contract', () => {
expect(exportSections({ seasonPasses: [{}], kidsFamily: { a: 1 } }).map((s) => s.key)).toEqual(['season_passes', 'kids_family']);
});
test('user.deleted waits while there is a registration for an event that has not ended', async () => {
mockBlockers = [{ eventTitle: 'Youth Camp', endDate: new Date('2027-03-14T12:00:00Z') }];
const reply = await handleAccountsCall({ ...base, type: 'user.deleted', approvedAt: base.occurredAt });
expect(userDeletedReplySchema.parse(reply)).toMatchObject({ status: 'deferred', reason: 'Has a registration for Youth Camp (2027-03-14)' });
expect(new Date((reply as { retryAfter: string }).retryAfter).getTime()).toBeGreaterThan(new Date('2027-03-14T12:00:00Z').getTime());
expect(mockAnonymised).toEqual([]);
});
test('user.deleted anonymises, signs them out here and unlinks the account', async () => {
const reply = await handleAccountsCall({ ...base, type: 'user.deleted', approvedAt: base.occurredAt });
expect(reply).toEqual({ schema: IDENTITY_SCHEMA, status: 'deleted' });
expect(mockAnonymised).toEqual(['u1']);
expect(mockUsers.get('u1')).toMatchObject({ accountId: null, tokenVersion: 1 });
});
test('a call for someone Events doesn\'t know is answered as done', async () => {
const other = { ...base, sub: '8d2e4f6a-1b3c-4d5e-8f7a-9b0c1d2e3f4a' };
expect(await handleAccountsCall({ ...other, type: 'user.deleted', approvedAt: base.occurredAt })).toEqual({ schema: IDENTITY_SCHEMA, status: 'deleted' });
const exp = await handleAccountsCall({ ...other, type: 'user.export', exportId: '1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c' });
expect((exp as { sections: unknown[] }).sections).toEqual([]);
});
@@ -0,0 +1,83 @@
// 3.6.0: the nightly people check against Accounts (contracts 1.14.0 people.check).
type U = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
let mockUsers: U[] = [];
const mockUpdated: string[] = [];
const mockCalls: { type: string; sub: string }[] = [];
const mockErrors: string[] = [];
let mockMode = true;
let mockLinked = true;
let mockDeferred = new Set<string>();
jest.mock('../src/config/db', () => ({
user: {
findMany: async ({ take, cursor }: { take: number; cursor?: { id: string } }) => {
const sorted = [...mockUsers].sort((a, b) => a.id.localeCompare(b.id));
const start = cursor ? sorted.findIndex((u) => u.id === cursor.id) + 1 : 0;
return sorted.slice(start, start + take);
},
},
}));
jest.mock('../src/accounts/mode', () => ({ viaAccounts: async () => mockMode }));
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => (mockLinked ? { installId: 'acc-1' } : null), accounts: async () => { throw new Error('not in tests'); } }));
jest.mock('../src/accounts/signin', () => ({ updateLocalCopy: async (id: string) => { mockUpdated.push(id); } }));
jest.mock('../src/accounts/calls', () => ({
handleAccountsCall: async (c: { type: string; sub: string }) => { mockCalls.push(c); return { status: mockDeferred.has(c.sub) ? 'deferred' : 'deleted' }; },
}));
jest.mock('../src/accounts/status', () => ({ recordSignInError: async (_c: string, m: string) => { mockErrors.push(m); } }));
import type { PeopleCheckReply, Profile } from '@crosscode/contracts';
import { runPeopleCheck, sameAsLocal } from '../src/accounts/peopleCheck';
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
const user = (n: number, over: Partial<U> = {}): U => ({ id: `u${String(n).padStart(3, '0')}`, accountId: sub(n), name: `Person ${n}`, email: `p${n}@hope.test`, phoneNumber: null, newsEmail: false, newsWhatsApp: false, ...over });
const profile = (u: U, over: Partial<Profile> = {}): Profile => ({ name: u.name, given_name: null, family_name: null, email: u.email, email_verified: true, phone_number: u.phoneNumber, phone_number_verified: false, news_consent: { email: u.newsEmail, whatsapp: u.newsWhatsApp }, ...over });
beforeEach(() => {
mockUsers = []; mockUpdated.length = 0; mockCalls.length = 0; mockErrors.length = 0;
mockMode = true; mockLinked = true; mockDeferred = new Set();
});
test('updates only copies that differ, handles deleted accounts as user.deleted does, counts the rest', async () => {
mockUsers = [user(1), user(2), user(3), user(4), user(5)];
mockDeferred = new Set([sub(4)]);
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({
schema: 'crosscode.identity-request/1',
people: subs.map((s) => {
const u = mockUsers.find((x) => x.accountId === s)!;
if (s === sub(1)) return { sub: s, status: 'active' as const, profile: profile(u) };
if (s === sub(2)) return { sub: s, status: 'active' as const, profile: profile(u, { name: 'New Name', news_consent: { email: true, whatsapp: false } }) };
if (s === sub(3) || s === sub(4)) return { sub: s, status: 'deleted' as const, profile: null };
return { sub: s, status: 'unknown' as const, profile: null };
}),
});
expect(await runPeopleCheck({ ask, pageSize: 2 })).toEqual({ checked: 5, updated: 1, deleted: 1, deferred: 1, deactivated: 0, unknown: 1 });
expect(mockUpdated).toEqual(['u002']);
expect(mockCalls.map((c) => [c.type, c.sub])).toEqual([['user.deleted', sub(3)], ['user.deleted', sub(4)]]);
});
test('stops, changing nothing, when Accounts knows hardly anyone (linked to the wrong Accounts?)', async () => {
mockUsers = Array.from({ length: 12 }, (_, i) => user(i + 1));
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({ schema: 'crosscode.identity-request/1', people: subs.map((s) => ({ sub: s, status: 'unknown' as const, profile: null })) });
await expect(runPeopleCheck({ ask })).rejects.toThrow(/doesn't know 12 of 12/);
expect(mockCalls).toEqual([]);
expect(mockErrors).toHaveLength(1);
});
test('skipped on its own sign-in, or without a link', async () => {
mockMode = false;
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
mockMode = true; mockLinked = false;
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
});
test('sameAsLocal ignores email case and what Events doesn\'t keep', () => {
const u = user(1, { email: 'Jane@Hope.test' });
expect(sameAsLocal(u, profile(u, { email: 'jane@hope.test', email_verified: false, given_name: 'Jane' }))).toBe(true);
expect(sameAsLocal(u, profile(u, { phone_number: '+27821234567' }))).toBe(false);
});
test('an Accounts before 1.5.0 (people.check unknown there) skips the check instead of failing every night', async () => {
mockUsers = [user(1)];
const ask = async () => { throw Object.assign(new Error('Not a crosscode.identity-request/1 request: type Invalid input'), { code: 'INVALID_REQUEST' }); };
expect(await runPeopleCheck({ ask })).toEqual({ skipped: expect.stringContaining('1.5.0') });
});
@@ -0,0 +1,39 @@
// 3.3.0: new demo data (set-demo) removes the last demo's people from the church's Accounts
// (contracts 1.11.0 people.removeDemo), only while sign-in goes through Accounts.
const mockRequests: Record<string, unknown>[] = [];
let mockMode = 'accounts';
jest.mock('../src/config/db', () => ({}));
jest.mock('../src/accounts/client', () => ({
accounts: async () => ({
request: async (body: { subs: string[] }) => { mockRequests.push(body); return { removed: body.subs.length - 1, kept: [{ sub: body.subs[0], reason: 'not_demo' }] }; },
}),
accountsLink: async () => null,
AccountsUnavailable: class extends Error {},
}));
jest.mock('../src/accounts/mode', () => ({
...jest.requireActual('../src/accounts/mode'),
authMode: async () => mockMode,
}));
import { removeDemoPeople } from '../src/accounts/move';
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
beforeEach(() => { mockRequests.length = 0; mockMode = 'accounts'; });
test('asks Accounts to remove each old demo person once, a thousand at a time', async () => {
const subs = Array.from({ length: 1500 }, (_, i) => sub(i));
const r = await removeDemoPeople([...subs, subs[0]!, ''], 'admin-sub');
expect(mockRequests.map((q) => (q.subs as string[]).length)).toEqual([1000, 500]);
expect(mockRequests[0]).toMatchObject({ type: 'people.removeDemo', actor: 'admin-sub' });
expect(r).toEqual({ removed: 1498, kept: 2 });
});
test('nothing to ask while sign-in is Events\' own, or with nobody to remove', async () => {
mockMode = 'events';
expect(await removeDemoPeople([sub(1)])).toEqual({ removed: 0, kept: 0 });
mockMode = 'accounts';
expect(await removeDemoPeople([])).toEqual({ removed: 0, kept: 0 });
expect(mockRequests).toHaveLength(0);
});
@@ -0,0 +1,32 @@
// 3.5.0: how people sign in, for the Hub (heartbeat stats.signIn, contracts 1.13.0).
import { hub } from '@crosscode/contracts';
const mockSettings = new Map<string, string>();
let mockMode = 'accounts';
let mockLink: object | null = null;
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
jest.mock('../src/accounts/mode', () => ({
authMode: async () => mockMode,
getSetting: async (k: string) => mockSettings.get(k) ?? null,
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
}));
import { clearSignInError, recordSignInError, signInStatus } from '../src/accounts/status';
beforeEach(() => { mockSettings.clear(); mockMode = 'accounts'; mockLink = null; });
test('Accounts mode without a link, and why the last sign-in failed', async () => {
await recordSignInError('ACCOUNTS_UNAVAILABLE', 'Accounts isn\'t connected.\nConnect it under Settings → Linked products.', new Date('2026-11-20T10:00:00.000Z'));
const s = await signInStatus();
expect(s).toEqual({ mode: 'accounts', accounts: null, lastError: { at: '2026-11-20T10:00:00.000Z', code: 'ACCOUNTS_UNAVAILABLE', message: 'Accounts isn\'t connected. Connect it under Settings → Linked products.' } });
// It fits the heartbeat's contract.
expect(hub.eventsStatsSchema.shape.signIn.safeParse(s).success).toBe(true);
await clearSignInError();
expect((await signInStatus()).lastError).toBeNull();
});
test('linked: the Accounts install and its address', async () => {
mockLink = { installId: 'acc-1', url: 'https://accounts.hope.test', secret: 'x', updatedAt: new Date() };
expect((await signInStatus()).accounts).toEqual({ installId: 'acc-1', url: 'https://accounts.hope.test' });
});

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