Compare commits

..
Author SHA1 Message Date
joshua 0b70a87669 Merge branch 'fix/branding-upload-routing' 2026-11-20 14:28:16 +02:00
joshuaandClaude Opus 5.5 ead07ef932 docs: Events 3.6.1 in CHANGELOG, VERSIONS and HANDOVER (FastPanel sites)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:28:15 +02:00
joshuaandClaude Opus 5.5 d8312f4b33 Events 3.6.1: branding uploads work behind a proxy with extension rules
The logo/favicon upload succeeded, but the check that the site can show it
got a 404: on events-demo every /api/... path ending in a file extension
(.png, .ico, .pdf, .json) went to Next.js instead of the backend.

- next.config.ts: /api/* and /uploads/* that reach the site are passed to
  the backend (beforeFiles rewrites) via the new BACKEND_INTERNAL_URL
  (http://127.0.0.1:<apiPort>, from env.template.json on deploy). The e2e
  E2E_API_PROXY uses the same rewrites.
- nginx written by both installers and shown in DEPLOYMENT.md: /api/ and
  /uploads/ use location ^~ so no regex location can take them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:08:11 +02:00
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
135 changed files with 8121 additions and 410 deletions
+107
View File
@@ -2,6 +2,113 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## events@3.6.1 - 2026-11-20
- **Events 3.6.1 (fix):** uploading a logo or favicon failed with "uploaded, but the site can't
show it yet" behind a proxy with a file-extension rule (FastPanel's static-file handling sent
`/api/uploads/…png` to the frontend). The site now passes `/api/*` and `/uploads/*` that reach
it on to the backend (new `BACKEND_INTERNAL_URL`, added on deploy).
- **crosscode script:** the nginx site it writes uses `location ^~ /api/` and `^~ /uploads/`.
## accounts@1.6.0 - 2026-11-20
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp for a verified number) after every
sign-in, as Cross Events' own sign-in did; Sign-in settings → `signin_notices` turns it off.
## events@3.6.0, accounts@1.5.0, contracts@1.14.0 - 2026-11-20
A nightly check that each site's copies of people match their church accounts, for changes that
never arrived.
- **Contracts 1.14.0:** `people.check` in `crosscode.identity-request/1` (`PEOPLE_CHECK_MAX` 500)
and `peopleCheckReplySchema` (each sub `active` / `deactivated` / `deleted` / `unknown`, with the
profile for the first two). Samples and JSON Schema `people-check-reply`.
- **Accounts 1.5.0:** answers it, only with profiles of people the product knows.
- **Events 3.6.0:** the `accounts-people-check` job (04:30): fixes out-of-date copies, handles
deleted accounts as `user.deleted`, and stops if most people are unknown (wrong Accounts?).
## events@3.5.0, contracts@1.13.0, agent@1.3.1 - 2026-11-20
- **Agent 1.3.1:** agent 1.3.0 still reported itself as 1.2.0 (`AGENT_VERSION` in `src/stats.ts`
wasn't bumped with `package.json`), so the Hub refused `.env` jobs on it. Use 1.3.1.
Loading demo data left a site that signs in through Accounts with no Accounts link, so nobody could
sign in (`ACCOUNTS_UNAVAILABLE`, found on events-demo). The Hub (2.9.0) now sees it.
- **Contracts 1.13.0:** `stats.signIn` in the Cross Events heartbeat (mode, the linked Accounts,
the last sign-in failure; optional).
- **Events 3.5.0:** `set-demo.js` keeps `ProductLink` and `LinkNonce`; a site in Accounts mode
without a link reconnects at its next heartbeat even after an earlier auto-connect; sign-in
failures (start, finish, Accounts unreachable) are kept and sent to the Hub; What's New notes for
3.4.0 (and Accounts 1.4.0) that were missing.
## events@3.4.0, accounts@1.4.0, contracts@1.12.0, agent@1.3.0, crosscode script - 2026-11-20
Background jobs are switched on and off (and rescheduled) from each site's admin, over the .env;
Accounts' emails look like Cross Events'; the Hub shows and changes an install's .env (Hub 2.8.0).
- **Contracts 1.12.0:** `env-read` and `env-set` agent jobs, `envReadResultSchema`,
`isSecretEnvName` / `SECRET_ENV_NAME`, `ENV_JOBS_MIN_AGENT` (1.3.0). `env-set` refuses secrets,
newlines, files other than `backend/.env` / `frontend/.env.production`, and empty changes.
- **crosscode script:** `crosscode env <church> <product>` prints the product's .env values
(secrets only as set or not); with `--set NAME=value`, `--unset NAME` and `--restart` it changes
one file (a copy is kept, the last 5), rebuilds the frontend when its file changed, reloads, and
waits for `/health`; if that fails the file is put back (and rebuilt). Secrets and generated
values are refused (`lib/envedit.cjs`). Tests: `scripts/tests/envedit.bats`.
- **Agent 1.3.0:** runs `env-read` and `env-set` as `crosscode env`.
- **Events 3.4.0:** Settings → Background jobs switches each job on or off and changes its
schedule; the choice is kept in the database, wins over the .env and applies straight away.
- **Accounts 1.4.0:** Admin → Background jobs (the same as Events'); every email is styled as
Cross Events' (church colour and logo, a button, contact details), with the same plain text.
## events@3.3.0, accounts@1.3.0, contracts@1.11.0 - 2026-11-20
Accounts looks like Cross Events and backs itself up; fixes in Events' sign-out and branding uploads.
- **Contracts 1.11.0:** `people.removeDemo` in `crosscode.identity-request/1` (and its reply):
new demo data in a product removes the old demo people's accounts. Only `@example.com` addresses
(`DEMO_EMAIL_DOMAIN`), never an Accounts admin.
- **Accounts 1.3.0:** the account and admin pages in Cross Events' layout (top bar, sidebar of
sections with their own addresses, dark footer); quick links to the church's sites; nightly
database backups with an admin Backups page; a fuller built-in privacy notice; its own favicon.
- **Events 3.3.0:** signing out also signs out of Accounts; uploaded logos and favicons are served
from the folder they're saved in; new demo data replaces the old demo people in Accounts.
## events@3.2.0, contracts@1.10.0 - 2026-11-19
Emergency updates can run as soon as possible (Hub 2.7.0); the Hub asks again when an event is on.
- **Contracts 1.10.0:** `stats.live` in the Cross Events heartbeat (`eventsNow`, `checkInsLastHour`;
optional).
- **Events 3.2.0:** sends it (sessions or one-day events on now, check-ins in the last hour).
## events@3.1.0, accounts@1.2.0, contracts@1.9.0 - 2026-11-19
A church moved Cross Events' sign-in to Accounts without email set up in Accounts: Accounts couldn't
send codes or password links, sign-in failed with a 500, and nobody could get in.
- **Contracts 1.9.0:** `messaging.status`, `messaging.test`, `messaging.set` in
`crosscode.identity-request/1` (SMTP and WAWP settings, secrets sealed); `people.ensure` answers
`emailSent`.
- **Accounts 1.2.0:** a code or link that can't be sent shows a message instead of a 500 (WhatsApp
codes fall back to email); forgot password says email isn't set up; the `messaging.*` requests
(test, and save only what worked); a test WhatsApp in its admin; WAWP from the `.env` too.
- **The sign-in pages look like the church's site:** `@crosscode/ui` Shell / Card / Heading redone
(colour wash, logo and name, cards edged in the church's colour, icons); Events sends its logo and
colours (`church.branding`, and with a move).
- **Events 3.1.0:** Settings → Sign-in shows what Accounts can send and sets it up by copying this
site's SMTP / WAWP (its secrets stay on the server), with a test before saving; the move needs
Accounts' email (disabled, and refused by the server, without it).
## crosscode script - 2026-11-19 (no tag: servers run `main`)
- **A church with Accounts couldn't be updated.** `crosscode install` / `add` writes Accounts' PM2
config to `apps/accounts/ecosystem.config.cjs`, which no `.gitignore` covered, so the next
`deploy` stopped at "files … were changed or added by hand: ?? apps/accounts/ecosystem.config.cjs".
The PM2 configs crosscode makes (`apps/events/ecosystem.config.js`, `apps/accounts/ecosystem.config.cjs`)
no longer count as changes by hand, also in checkouts of releases that don't ignore them, and
`apps/accounts/.gitignore` ignores it from the next Accounts release on. bats test.
## events@3.0.0, accounts@1.1.0, contracts@1.8.0, crosscode script - 2026-11-19
Cross Events signs in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md).
+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
+123
View File
@@ -1,5 +1,128 @@
# 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.
+41
View File
@@ -3,6 +3,47 @@
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,
+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.1.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",
+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) => {
@@ -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,
@@ -99,19 +99,23 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
};
if (stage === 'password' || stage === 'done') return base;
const a = await account(ctx, pending);
let sentNow: string | null = null;
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
sentNow = sent.sentTo;
}
const extra: Record<string, unknown> = { name: a.name, email: a.email };
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
if (stage === 'two_factor') {
extra.method = a.twoFactorMethod;
if (a.twoFactorMethod !== 'totp') extra.sentTo = maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
// Where it actually went (a WhatsApp code that couldn't go was sent by email).
if (a.twoFactorMethod !== 'totp') extra.sentTo = sentNow ?? maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
}
if (stage === 'setup_two_factor') {
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
// Only the ways that can deliver a code now (1.2.0): an app always works.
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
extra.why = a.role === 'admin' ? 'admin' : 'product';
}
if (stage === 'notice') {
@@ -8,7 +8,9 @@ import type Provider from 'oidc-provider';
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { clientIp, loginEvent } from '../lib/audit.js';
import { sendSignInNotice } from '../accounts/signInNotice.js';
import { resetPasswordEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { normaliseEmail } from '../accounts/service.js';
@@ -43,6 +45,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const clientId = String(details.params.client_id ?? '') || null;
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
await signedInThrough(ctx, clientId, pending.accountId);
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
return { stage: 'done', redirectTo, ...extra };
}
@@ -88,6 +92,8 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
// ─── Forgot / reset password ───────────────────────────────────────────────
r.post('/password/forgot', limit(5), handle(async (req) => {
// 1.2.0: without email nobody gets a link; say so (the same answer whoever asks).
if (!(await ctx.messenger.emailReady())) throw new ApiError(503, 'EMAIL_NOT_READY', 'Password reset links can\'t be sent right now: the church\'s email isn\'t set up. Please let the church office know.');
const email = normaliseEmail(req.body?.email);
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
// The same answer either way, so nobody can find out who has an account (Events 1.51.17).
@@ -95,11 +101,7 @@ export function interactionRouter(ctx: Ctx, provider: Provider) {
const token = randomToken();
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
await ctx.messenger.email({
to: a.email,
subject: 'Reset your password',
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
});
await ctx.messenger.email({ to: a.email, ...(await resetPasswordEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, minutes: RESET_MINUTES })) });
}
return { sent: true };
}));
+270 -23
View File
@@ -1,9 +1,16 @@
/**
* Background jobs on pg-boss (as Cross Events): one run per schedule however many processes run,
* and timers in this process if the queue can't start. JOBS_ENABLED=false turns them all off.
*
* 1.4.0 (as Events 3.4.0): Admin → Background jobs shows each job's schedule and last runs, runs
* one now, and switches one on or off or changes its schedule. That choice is kept in the
* database (`job_overrides`), wins over the .env (a job's own flag, e.g. BACKUP_ENABLED=false, and
* JOB_SCHEDULE_<NAME>) and takes effect straight away (in other processes within 30 seconds).
*/
import { CronExpressionParser } from 'cron-parser';
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { runBackupJob } from './backups/backups.js';
import { heartbeat } from './hub/client.js';
import { runDue } from './links/deliveries.js';
import { forgetOldRequests } from './links/requests.js';
@@ -11,15 +18,17 @@ import { deleteExpired } from './oidc/adapter.js';
import { runDeletionJob } from './privacy/deletion.js';
import { runExportsJob } from './privacy/export.js';
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
export type Job = { name: string; label: string; cron: string; env: string | null; run: (ctx: Ctx) => Promise<unknown> };
export const JOBS: Job[] = [
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
{ name: 'deliveries', label: 'Linked products: send what they need to know (sign-outs, changes), retrying failures', cron: '* * * * *', env: null, run: (ctx) => runDue(ctx) },
{ name: 'exports', label: 'Privacy: make the copies of their data people asked for', cron: '*/5 * * * *', env: 'EXPORTS_JOB_ENABLED', run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', label: 'Privacy: delete the accounts whose deletion is due', cron: '*/15 * * * *', env: 'DELETIONS_JOB_ENABLED', run: (ctx) => runDeletionJob(ctx) },
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
{ name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED', run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', label: 'Cross Code Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED', run: (ctx) => heartbeat(ctx) },
{
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
name: 'cleanup', label: 'Delete expired sign-ins, codes and links', cron: '17 * * * *', env: null,
run: async (ctx) => {
const now = ctx.now();
const [oidc, pending, tokens, nonces, requests] = await Promise.all([
@@ -34,23 +43,261 @@ export const JOBS: Job[] = [
},
];
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) return async () => {};
const tz = ctx.config.timezone;
const SCHEMA = 'pgboss_accounts';
const OVERRIDES_KEY = 'job_overrides';
const OVERRIDES_TTL_MS = 30_000;
export type Override = { enabled?: boolean; cron?: string };
type Run = { state: string; createdOn?: Date | null; startedOn: Date | null; completedOn: Date | null; output: unknown };
/** The running queue or timers, the admin's choices (cached), and a short history for timer mode. */
type State = {
mode: 'queue' | 'timers' | 'off';
boss: PgBoss | null;
timers: Map<string, NodeJS.Timeout>;
history: Map<string, Run[]>;
overrides: Record<string, Override>;
overridesAt: number;
env: NodeJS.ProcessEnv;
};
const state: State = { mode: 'off', boss: null, timers: new Map(), history: new Map(), overrides: {}, overridesAt: 0, env: process.env };
/** Tests: a different environment for the env flags and schedules. */
export function useEnvForTest(env: NodeJS.ProcessEnv): void {
state.env = env;
}
const flag = (name: string | null) => {
if (!name) return true;
const v = state.env[name];
return v === undefined || v === '' ? true : String(v).toLowerCase() !== 'false';
};
export function isCron(cron: unknown, tz = 'Africa/Johannesburg'): cron is string {
if (typeof cron !== 'string' || cron.trim().split(/\s+/).length !== 5) return false;
try {
const boss = new PgBoss({ connectionString, schema: 'pgboss_accounts', application_name: 'crosscode-accounts-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
await boss.schedule(job.name, job.cron, undefined, { tz });
await boss.work(job.name, async () => job.run(ctx));
}
console.log(`[jobs] Job queue started: ${JOBS.map((j) => j.name).join(', ')}.`);
return async () => { await boss.stop({ graceful: true }); };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
const timers = JOBS.map((job) => setInterval(() => { job.run(ctx).catch((err) => console.warn(`[jobs] ${job.name}:`, (err as Error).message)); }, job.everyMs));
return async () => { timers.forEach(clearInterval); };
CronExpressionParser.parse(cron, { tz });
return true;
} catch {
return false;
}
}
export async function loadOverrides(ctx: Ctx, force = false): Promise<Record<string, Override>> {
if (!force && state.overridesAt && Date.now() - state.overridesAt < OVERRIDES_TTL_MS) return state.overrides;
try {
// Straight from the table: Settings caches for 30 s too, and a save must show at once here.
const row = await ctx.db.appSetting.findUnique({ where: { key: OVERRIDES_KEY } });
const parsed = row?.value ? JSON.parse(row.value) : {};
state.overrides = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
state.overridesAt = Date.now();
} catch (e) {
if (force) console.warn('[jobs] Could not read the job overrides:', (e as Error).message);
}
return state.overrides;
}
/** Whether the .env switches a job on (its own flag; JOBS_ENABLED aside). */
export const envEnabled = (job: Job) => flag(job.env);
/** JOBS_ENABLED=false turns all off; then the admin's choice; then the job's env flag. */
export function isEnabled(ctx: Ctx, job: Job): boolean {
if (!ctx.config.jobsEnabled) return false;
const o = state.overrides[job.name];
if (o && typeof o.enabled === 'boolean') return o.enabled;
return envEnabled(job);
}
/** The .env's schedule (JOB_SCHEDULE_<NAME>, checked) or the job's own. */
export function envCronFor(ctx: Ctx, job: Job): string {
const v = state.env[`JOB_SCHEDULE_${job.name.toUpperCase().replace(/-/g, '_')}`];
if (v && isCron(v, ctx.config.timezone)) return v;
if (v) console.warn(`[jobs] Ignoring invalid schedule for ${job.name}: "${v}"`);
return job.cron;
}
export function cronFor(ctx: Ctx, job: Job): string {
const o = state.overrides[job.name];
if (o && isCron(o.cron, ctx.config.timezone)) return o.cron;
return envCronFor(ctx, job);
}
export const nextRun = (cron: string, tz: string, from = new Date()) => CronExpressionParser.parse(cron, { tz, currentDate: from }).next().toDate();
function remember(name: string, run: Run) {
state.history.set(name, [run, ...(state.history.get(name) ?? [])].slice(0, 10));
}
async function runJob(ctx: Ctx, job: Job) {
return (await job.run(ctx)) ?? null;
}
function startTimer(ctx: Ctx, job: Job) {
const tz = ctx.config.timezone;
const scheduleNext = () => {
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const delay = Math.max(1000, nextRun(cronFor(ctx, job), tz).getTime() - Date.now());
state.timers.set(job.name, setTimeout(async () => {
await loadOverrides(ctx);
if (!isEnabled(ctx, job)) { state.timers.delete(job.name); return; }
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
console.warn(`[jobs] ${job.name}:`, (e as Error).message);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
scheduleNext();
}
}, Math.min(delay, 2 ** 31 - 1)));
};
scheduleNext();
}
async function applyJob(ctx: Ctx, job: Job) {
if (state.mode === 'queue' && state.boss) {
if (isEnabled(ctx, job)) await state.boss.schedule(job.name, cronFor(ctx, job), undefined, { tz: ctx.config.timezone });
else await state.boss.unschedule(job.name).catch(() => {});
} else if (state.mode === 'timers') {
clearTimeout(state.timers.get(job.name));
state.timers.delete(job.name);
startTimer(ctx, job);
}
}
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) {
state.mode = 'off';
return async () => {};
}
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
try {
const boss = new PgBoss({ connectionString, schema: SCHEMA, application_name: 'crosscode-accounts-jobs' });
boss.on('error', (e: Error) => console.warn('[jobs]', e.message));
await boss.start();
state.boss = boss;
state.mode = 'queue';
for (const job of JOBS) {
await boss.createQueue(job.name, { policy: 'stately' }).catch(() => {});
// Every job has a worker (an admin can switch one on later); only those on are scheduled.
await boss.work(job.name, async (batch) => {
await loadOverrides(ctx);
const manual = (Array.isArray(batch) ? batch : [batch]).some((j) => (j as { data?: { manual?: boolean } })?.data?.manual);
if (!manual && !isEnabled(ctx, job)) return { skipped: 'switched off' };
return runJob(ctx, job);
});
if (isEnabled(ctx, job)) await boss.schedule(job.name, cronFor(ctx, job), undefined, { tz });
else await boss.unschedule(job.name).catch(() => {});
}
const off = JOBS.filter((j) => !isEnabled(ctx, j)).map((j) => j.name);
console.log(`[jobs] Job queue started: ${JOBS.filter((j) => isEnabled(ctx, j)).map((j) => j.name).join(', ')}${off.length ? ` (off: ${off.join(', ')})` : ''}.`);
return async () => { await boss.stop({ graceful: true }); state.boss = null; state.mode = 'off'; };
} catch (e) {
console.warn('[jobs] Job queue unavailable, using timers:', (e as Error).message);
state.boss = null;
state.mode = 'timers';
for (const job of JOBS) startTimer(ctx, job);
return async () => { state.timers.forEach(clearTimeout); state.timers.clear(); state.mode = 'off'; };
}
}
export class JobError extends Error {
constructor(public status: number, message: string) { super(message); }
}
/**
* Saves an admin's choice for one job and applies it. `enabled` / `cron`: a value wins over the
* .env, null goes back to it, undefined leaves it.
*/
export async function setOverride(ctx: Ctx, name: string, change: { enabled?: unknown; cron?: unknown }): Promise<{ enabled: boolean | null; cron: string | null }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
const { enabled, cron } = change;
if (enabled !== undefined && enabled !== null && typeof enabled !== 'boolean') throw new JobError(400, '"enabled" must be true, false or null.');
if (cron !== undefined && cron !== null && cron !== '' && (typeof cron !== 'string' || cron.length > 100 || !isCron(cron.trim(), ctx.config.timezone))) {
throw new JobError(400, 'That schedule isn\'t a cron expression with five fields (minute hour day month weekday), e.g. "*/10 * * * *".');
}
const all = { ...(await loadOverrides(ctx, true)) };
const entry: Override = { ...(all[name] ?? {}) };
if (enabled !== undefined) { if (enabled === null) delete entry.enabled; else entry.enabled = enabled as boolean; }
if (cron !== undefined) { if (cron === null || cron === '') delete entry.cron; else entry.cron = (cron as string).trim(); }
if (Object.keys(entry).length) all[name] = entry; else delete all[name];
const value = JSON.stringify(all);
await ctx.db.appSetting.upsert({ where: { key: OVERRIDES_KEY }, update: { value }, create: { key: OVERRIDES_KEY, value } });
ctx.settings.forget();
state.overrides = all;
state.overridesAt = Date.now();
await applyJob(ctx, job);
return { enabled: typeof entry.enabled === 'boolean' ? entry.enabled : null, cron: entry.cron ?? null };
}
/** Runs a job now: queued in queue mode (it runs even when switched off), here otherwise. */
export async function runNow(ctx: Ctx, name: string): Promise<{ queued: boolean; output?: unknown }> {
const job = JOBS.find((j) => j.name === name);
if (!job) throw new JobError(404, 'There\'s no such job.');
if (state.mode === 'queue' && state.boss) {
await state.boss.send(job.name, { manual: true }, { singletonKey: `${job.name}-manual` });
return { queued: true };
}
const entry: Run = { state: 'active', startedOn: new Date(), completedOn: null, output: null };
try {
entry.output = await runJob(ctx, job);
entry.state = 'completed';
return { queued: false, output: entry.output };
} catch (e) {
entry.state = 'failed';
entry.output = { message: (e as Error).message };
throw new JobError(502, `The job failed: ${(e as Error).message}`);
} finally {
entry.completedOn = new Date();
remember(job.name, entry);
}
}
/** Each job with its switch, schedule, what the .env says, the admin's choice, and its last runs. */
export async function jobStatus(ctx: Ctx) {
await loadOverrides(ctx, true);
const tz = ctx.config.timezone;
const recent = new Map<string, Run[]>();
if (state.mode === 'queue') {
try {
// As in Cross Events: timestamptz as plain UTC, so Prisma's pg adapter doesn't drop the offset.
const rows = await ctx.db.$queryRawUnsafe<(Run & { name: string })[]>(`
SELECT name, state, created_on AT TIME ZONE 'UTC' AS "createdOn", started_on AT TIME ZONE 'UTC' AS "startedOn",
completed_on AT TIME ZONE 'UTC' AS "completedOn", output
FROM (
SELECT name, state::text, created_on, started_on, completed_on, output,
row_number() OVER (PARTITION BY name ORDER BY created_on DESC) AS rn
FROM ${SCHEMA}.job WHERE name = ANY($1::text[])
) ranked WHERE rn <= 10 ORDER BY "createdOn" DESC`, JOBS.map((j) => j.name));
for (const r of rows) recent.set(r.name, [...(recent.get(r.name) ?? []), r]);
} catch (e) {
console.warn('[jobs] Could not read the run history:', (e as Error).message);
}
} else {
for (const [name, list] of state.history) recent.set(name, list);
}
return {
mode: state.mode,
timezone: tz,
jobsEnabledEnv: ctx.config.jobsEnabled,
jobs: JOBS.map((job) => {
const cron = cronFor(ctx, job);
const enabled = isEnabled(ctx, job);
const o = state.overrides[job.name] ?? {};
return {
name: job.name, label: job.label, cron, enabled, envFlag: job.env,
envEnabled: envEnabled(job), envCron: envCronFor(ctx, job), defaultCron: job.cron,
override: { enabled: typeof o.enabled === 'boolean' ? o.enabled : null, cron: isCron(o.cron, tz) ? o.cron : null },
nextRun: enabled && state.mode !== 'off' ? nextRun(cron, tz) : null,
recent: recent.get(job.name) ?? [],
};
}),
};
}
+9
View File
@@ -20,9 +20,15 @@ export type Config = {
hubAdminEmail: string | null;
timezone: string;
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
/** 1.2.0: WAWP from the .env when the database has none (as Cross Events). */
wawp: { accessToken: string; instanceId: string } | null;
/** Local testing only: linked products on http or private addresses. */
allowPrivateLinks: boolean;
jobsEnabled: boolean;
/** 1.3.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */
databaseUrl: string | null;
/** 1.3.0: where backups go; default backend/backups (tests use their own folder). */
backupDir: string | null;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
@@ -67,7 +73,10 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
smtp: env.SMTP_HOST
? { host: env.SMTP_HOST, port: Number(env.SMTP_PORT || 587), user: env.SMTP_USER || '', pass: env.SMTP_PASS || '', from: env.SMTP_FROM || env.SMTP_USER || '', secure: bool(env.SMTP_SECURE, Number(env.SMTP_PORT) === 465) }
: null,
wawp: env.WAWP_ACCESS_TOKEN && env.WAWP_INSTANCE_ID ? { accessToken: env.WAWP_ACCESS_TOKEN, instanceId: env.WAWP_INSTANCE_ID } : null,
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
jobsEnabled: bool(env.JOBS_ENABLED, true),
databaseUrl: env.DATABASE_URL?.trim() || null,
backupDir: null,
};
}
+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',
]);
+136 -19
View File
@@ -15,20 +15,25 @@ import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import type Provider from 'oidc-provider';
import {
ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
type IdentityRequest, type ImportPerson, type ImportResult,
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
} from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import type { ProductLink } from '../generated/prisma/client.js';
import { limit } from '../http.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { newAccountEmail, testEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { appVersion } from '../lib/version.js';
import { BUILT_IN_VERSION } from '../privacy/notice.js';
import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js';
import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent } from '../accounts/service.js';
import { turnOff } from '../accounts/twoFactor.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { anonymise } from '../privacy/deletion.js';
/** 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) {
@@ -166,13 +171,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await ctx.db.privacyNotice.create({ data: { version: n.version, title: n.title, body: n.body, publishedAt: new Date(n.publishedAt), publishedById: null } });
}
}
const stored = await ctx.settings.json<Record<string, unknown> & { branding?: { colours?: { primary?: string; accent?: string } } }>('church_profile', {});
const next = { ...stored };
if (!stored.name && r.church.name) next.name = r.church.name;
if (!stored.branding?.colours?.primary && r.church.primaryColour) {
next.branding = { logoUrl: null, iconUrl: null, ...(stored.branding ?? {}), colours: { accent: '#f2a900', ...(stored.branding?.colours ?? {}), primary: r.church.primaryColour } } as never;
}
if (JSON.stringify(next) !== JSON.stringify(stored)) await ctx.settings.set('church_profile', JSON.stringify(next));
await applyLook(ctx, r.church, false);
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: ctx.now() } });
await logRequest(ctx, link, r, 'import_started', null, req, { notices: noticesTaken ? r.notices.length : 0 });
}
@@ -226,15 +225,18 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
// Only the product's own address: never somewhere else.
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), returnUrl, expiresAt: new Date(ctx.now().getTime() + SET_PASSWORD_DAYS * 86400e3) } });
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
await ctx.messenger.email({
to: email,
subject: `Your account at ${churchName}`,
text: `Hello ${r.name},\n\n${churchName} has made you an account. Choose your password here (the link works for ${SET_PASSWORD_DAYS} days):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you weren't expecting this, you can ignore this email.`,
});
// 1.2.0: the account stands even when the email can't go (they can use "Forgot your password?"
// once email works); the product is told.
let emailSent = true;
try {
await ctx.messenger.email({ to: email, ...(await newAccountEmail(ctx, { name: r.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, days: SET_PASSWORD_DAYS })) });
} catch (e) {
emailSent = false;
console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message);
}
await loginEvent(ctx, a.id, 'account_created', req, { clientId: link.installId, detail: { by: 'product', product: link.product } });
await logRequest(ctx, link, r, 'person_created_by_product', a.id, req);
return reply({ sub: a.id, created: true });
await logRequest(ctx, link, r, 'person_created_by_product', a.id, req, { emailSent });
return reply({ sub: a.id, created: true, emailSent });
}
case 'people.update': {
const a = await knownAccount(ctx, link, r.sub);
@@ -282,6 +284,88 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req);
return reply({ ok: true as const });
}
case 'people.removeDemo': {
// 1.3.0: a product's new demo data replaces the old; the old demo people's accounts go.
const kept: { sub: string; reason: 'not_demo' | 'admin' | 'unknown' }[] = [];
let removed = 0;
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: r.subs } }, select: { accountId: true } })).map((p) => p.accountId));
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: [...known] } } })).map((a) => [a.id, a]));
for (const sub of new Set(r.subs)) {
const a = accounts.get(sub);
if (!a || a.status === 'deleted') { kept.push({ sub, reason: 'unknown' }); continue; }
if (!isDemoEmail(a.email)) { kept.push({ sub, reason: 'not_demo' }); continue; }
if (a.role === 'admin') { kept.push({ sub, reason: 'admin' }); continue; }
await signOutEverywhere(ctx, provider, a.id);
await anonymise(ctx, a.id);
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
removed++;
}
await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length });
return reply({ removed, kept });
}
case 'people.check': {
// 1.5.0: the product's regular check that its copies are current. Profiles only for people
// this product knows; a deleted account is said to be deleted (its sub was that person's).
const subs = [...new Set(r.subs)];
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: subs } }, select: { accountId: true } })).map((p) => p.accountId));
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: subs } } })).map((a) => [a.id, a]));
const people = subs.map((sub) => {
const a = accounts.get(sub);
if (a?.status === 'deleted') return { sub, status: 'deleted' as const, profile: null };
if (!a || !known.has(sub)) return { sub, status: 'unknown' as const, profile: null };
return { sub, status: a.status === 'deactivated' ? 'deactivated' as const : 'active' as const, profile: profileOf(a) };
});
const count = (s: string) => people.filter((p) => p.status === s).length;
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
return reply({ people });
}
case '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 };
@@ -314,7 +398,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
}
const out = await handle(ctx, provider, link, secret, request, req);
// Checks write nothing, so they needn't be remembered.
const isCheck = 'check' in request && request.check;
// 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(() => {});
}
@@ -328,6 +413,38 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
return r;
}
/**
* The church's look on Accounts' pages from a product's (1.9.0): its name, logo and colours.
* `overwrite: false` (a move) fills only what's empty; `true` (an admin's button) replaces them.
* Returns the fields changed.
*/
async function applyLook(ctx: Ctx, look: ChurchLook, overwrite: boolean): Promise<string[]> {
type Stored = Record<string, unknown> & { name?: string; branding?: { logoUrl?: string | null; iconUrl?: string | null; colours?: { primary?: string; accent?: string | null } } };
const stored = await ctx.settings.json<Stored>('church_profile', {});
const branding = { logoUrl: null as string | null, iconUrl: null as string | null, ...(stored.branding ?? {}), colours: { primary: '#1f4e79', accent: '#f2a900', ...(stored.branding?.colours ?? {}) } };
const changed: string[] = [];
const take = (has: unknown, value: unknown) => value !== null && value !== undefined && value !== '' && (overwrite || !has);
const next: Stored = { ...stored };
if (take(stored.name, look.name)) { next.name = look.name!; changed.push('name'); }
if (take(stored.branding?.logoUrl, look.logoUrl)) { branding.logoUrl = look.logoUrl!; changed.push('logo'); }
if (take(stored.branding?.colours?.primary, look.primaryColour)) { branding.colours.primary = look.primaryColour!; changed.push('primary colour'); }
if (take(stored.branding?.colours?.accent && stored.branding?.colours?.accent !== '#f2a900', look.accentColour)) { branding.colours.accent = look.accentColour!; changed.push('accent colour'); }
if (!changed.length) return changed;
next.branding = branding;
next.updatedAt = ctx.now().toISOString();
await ctx.settings.set('church_profile', JSON.stringify(next));
return changed;
}
/** What can be sent now (no secrets), for a product's sign-in settings page. */
async function messagingStatus(ctx: Ctx) {
const emailReady = await ctx.messenger.emailReady();
return {
email: { ready: emailReady, host: emailReady ? ((await ctx.settings.get('smtp_host')) || ctx.config.smtp?.host || null) : null, from: emailReady ? ((await ctx.settings.get('smtp_from')) || ctx.config.smtp?.from || null) : null },
whatsapp: { ready: await ctx.messenger.whatsappReady(), instanceId: (await ctx.settings.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null },
};
}
/** 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) } } });
+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);
+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>/);
});
});
@@ -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');
});
});
@@ -177,6 +177,51 @@ describe('people.* from a product', () => {
assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.status, 'deactivated');
});
test('people.removeDemo removes only the product\'s demo people, never an admin or a real address', async () => {
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
const demo = await ensure('Old Demo', 'old.demo@example.com');
const real = await ensure('Real Person', 'real.person@hope.test');
const demoAdmin = await ensure('Demo Admin', 'demo.admin@example.com');
await h.db.account.update({ where: { id: demoAdmin }, data: { role: 'admin' } });
const stranger = (await h.makeAccount({ email: 'not.known@example.com' })).id;
const res = await ask({ type: 'people.removeDemo', subs: [demo, real, demoAdmin, stranger] });
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(res.body.removed, 1);
assert.deepEqual(res.body.kept, [{ sub: real, reason: 'not_demo' }, { sub: demoAdmin, reason: 'admin' }, { sub: stranger, reason: 'unknown' }]);
const gone = (await h.db.account.findUnique({ where: { id: demo } }))!;
assert.equal(gone.status, 'deleted');
assert.notEqual(gone.email, 'old.demo@example.com', 'the address is free for the next demo');
assert.equal((await h.db.account.findUnique({ where: { id: real } }))!.status, 'active');
assert.equal((await h.db.account.findUnique({ where: { id: stranger } }))!.status, 'active');
// The next demo can have the same person again, as a new account.
const again = await ask({ type: 'people.ensure', name: 'Old Demo', email: 'old.demo@example.com', phone: null, returnUrl: 'https://events.hope.test/' });
assert.equal(again.body.created, true);
});
test('1.5.0 people.check: profiles of the product\'s people, deleted accounts, and unknown for the rest; never stored', async () => {
const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string);
const known = await ensure('Check Known', 'check.known@hope.test');
const gone = await ensure('Check Gone', 'check.gone@hope.test');
await h.db.account.update({ where: { id: gone }, data: { status: 'deleted' } });
const off = await ensure('Check Off', 'check.off@hope.test');
await h.db.account.update({ where: { id: off }, data: { status: 'deactivated' } });
const stranger = (await h.makeAccount({ email: 'check.stranger@hope.test' })).id as string;
const nobody = crypto.randomUUID();
const requestId = crypto.randomUUID();
const res = await ask({ type: 'people.check', subs: [known, gone, off, stranger, nobody] }, { requestId });
assert.equal(res.status, 200, JSON.stringify(res.body));
const bySub = Object.fromEntries((res.body.people as { sub: string; status: string; profile: { name: string } | null }[]).map((p) => [p.sub, p]));
assert.equal(bySub[known]!.status, 'active');
assert.equal(bySub[known]!.profile!.name, 'Check Known');
assert.equal(bySub[gone]!.status, 'deleted');
assert.equal(bySub[gone]!.profile, null);
assert.equal(bySub[off]!.status, 'deactivated');
assert.deepEqual([bySub[stranger]!.status, bySub[stranger]!.profile], ['unknown', null], 'not known through this product: no profile');
assert.equal(bySub[nobody]!.status, 'unknown');
assert.equal(await h.db.productRequest.findUnique({ where: { requestId } }), null, 'the reply holds profiles: not kept');
});
test('a retry with the same request id gets the same answer; a bad signature is refused', async () => {
const requestId = crypto.randomUUID();
const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' };
@@ -0,0 +1,50 @@
// 1.6.0: a "New sign-in" email (and WhatsApp) after each sign-in, as Cross Events sends.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { startHarness, type Harness } from './support/harness.js';
import { describeDevice, sendSignInNotice } from '../src/accounts/signInNotice.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
const CHROME_WIN = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
describe('sign-in notices', () => {
test('an email with when, where, the device and the site; WhatsApp too for a verified number', async () => {
const m = h.ctx.messenger as MemoryMessenger;
const a = await h.makeAccount({ email: 'notice.person@hope.test' });
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: '127.0.0.1', userAgent: CHROME_WIN, clientId: 'accounts-self' }), 'sent');
const mail = m.emails.filter((e) => e.to === 'notice.person@hope.test').at(-1)!;
assert.match(mail.subject, /^New sign-in to your .+ account$/);
assert.match(mail.text, /Device: Chrome on Windows/);
assert.match(mail.text, /Signed in to: Your account page/);
assert.match(mail.html ?? '', /Not you\?/);
await h.db.account.update({ where: { id: a.id as string }, data: { phone: '+27821234567', phoneVerified: true } });
m.whatsappOn = true;
const before = m.whatsapps.length;
await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null });
assert.equal(m.whatsapps.length, before + 1);
assert.match(m.whatsapps.at(-1)!.text, /New sign-in/);
m.whatsappOn = false;
});
test('admins can switch them off; a failing email never throws', async () => {
const m = h.ctx.messenger as MemoryMessenger;
const a = await h.makeAccount({ email: 'notice.off@hope.test' });
await h.ctx.settings.set('signin_notices', 'false');
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'off');
await h.ctx.settings.set('signin_notices', null);
m.emailOn = false;
assert.equal(await sendSignInNotice(h.ctx, { accountId: a.id as string, ip: null, userAgent: null, clientId: null }), 'failed');
m.emailOn = true;
});
test('device names', () => {
assert.equal(describeDevice(CHROME_WIN), 'Chrome on Windows');
assert.equal(describeDevice('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1'), 'Safari on iPhone or iPad');
assert.equal(describeDevice(null), 'Unknown device');
});
});
+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.1.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,7 +13,7 @@ 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();
@@ -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";
@@ -88,7 +90,7 @@ export function SignIn({ uid }: { uid: string }) {
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>);
@@ -121,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 />
@@ -144,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")} />
@@ -162,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>
@@ -212,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) => (
@@ -243,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>
@@ -257,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>
</>
);
@@ -269,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" }] }],
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/agent",
"version": "1.2.0",
"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",
+10
View File
@@ -48,6 +48,16 @@ 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":
+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.2.0";
export const AGENT_VERSION = "1.3.1";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
+9
View File
@@ -45,6 +45,15 @@ describe("crosscode arguments for each job", () => {
.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"]);
+127
View File
@@ -5,6 +5,133 @@ 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.1] - 2026-11-20
### Fixed
- **Uploading a logo or favicon under Settings → Branding failed on some servers** with "The logo was
uploaded, but the site can't show it yet". The upload worked, but on a server whose proxy has a
rule for file extensions (static-file caching) every `/api/…` path ending in `.png`, `.ico`,
`.pdf`, `.json` and so on went to the site (Next.js), which answered 404. So the check after the
upload failed, as did pictures, certificate PDFs and `/api/v2/openapi.json`. Two changes:
- The site passes `/api/*` and `/uploads/*` that reach it on to the backend
(`next.config.ts` rewrites, `beforeFiles`). New frontend setting `BACKEND_INTERNAL_URL`
(`http://127.0.0.1:<apiPort>`, added to `.env.production` on deploy). Unset, nothing is
passed on, as before. The end-to-end tests' `E2E_API_PROXY` uses the same rewrites.
- The nginx site the installers write (and DEPLOYMENT.md) sends `/api/` and `/uploads/` to the
backend with `location ^~`, so no regex location can take them. Existing servers keep their
nginx file: change it by hand (DEPLOYMENT.md §4).
## [3.6.0] - 2026-11-20
Works with any Accounts; the people check needs Accounts 1.5.0 (with an older one it's skipped).
### Added
- **The nightly people check** (`accounts-people-check`, 04:30, `ACCOUNTS_PEOPLE_CHECK_ENABLED`,
`src/accounts/peopleCheck.ts`). In Accounts mode it sends every linked person's `sub` to
Accounts, 500 at a time (`people.check`, contracts 1.14.0), and: updates the local copy where the
name, email, phone or news choices differ (as `user.updated`); handles deleted accounts as
`user.deleted` (anonymised, or deferred while there's a registration for an event that hasn't
ended); counts deactivated and unknown people. When more than half a page (10+) is unknown, the
site is probably linked to the wrong Accounts: the check stops, changes nothing for them, fails
(Background jobs, the Hub's "jobs failing") and records why (the Hub's "sign-in failed" alert).
## [3.5.0] - 2026-11-20
### Fixed
- **After "Load demo data" nobody could sign in** ("Sign-in isn't available right now",
`ACCOUNTS_UNAVAILABLE`). `scripts/set-demo.js` emptied `ProductLink` (it keeps only a few tables)
but kept `AppSetting`, so the site stayed in Accounts mode with no Accounts link, and
`accounts_auto_connected` stopped it reconnecting. Demo data now keeps `ProductLink` and
`LinkNonce`, and a site in Accounts mode without a link connects to the Accounts the Hub lists at
its next heartbeat whatever happened before (a site on its own sign-in still keeps an admin's
Disconnect).
### Added
- Heartbeat `stats.signIn` (contracts 1.13.0): the sign-in mode, the linked Accounts (install id and
address) and the last failure to start or finish a sign-in (`accounts_last_signin_error`, cleared
by the next sign-in that works). The Hub 2.9.0 alerts on it.
## [3.4.0] - 2026-11-20
### Added
- **Background jobs are switched on and off from Settings → Background jobs.** Each job has a
switch and a Schedule button (presets or a cron expression). The choice is saved in the database
(`AppSetting` `job_overrides`), wins over the .env (the job's own flag such as
`WAITLIST_JOB_ENABLED`, and `JOB_SCHEDULE_<NAME>`), and applies straight away: the queue is
rescheduled in this process, and other processes see it within 30 seconds (a run of a job switched
off elsewhere is skipped). "use the .env" goes back to what the server says.
`JOBS_ENABLED=false` still turns every job off (the end-to-end tests use it).
API: `PUT /api/v2/admin/jobs/:name` `{ enabled, cron }` (null goes back to the .env); `GET
/admin/jobs` also gives `envEnabled`, `envCron`, `defaultCron` and `override`.
### Changed
- "Run now" also works for a job that's switched off.
## [3.3.0] - 2026-11-20
Works with Accounts 1.3.0 (needed for the demo-data part; with an older Accounts the old demo people
just stay there).
### Fixed
- **An uploaded logo or favicon could point at a file that "didn't exist".** Uploads were saved in
`backend/public/uploads` but served from `public/uploads` under whatever folder the backend
was started from, so a backend started elsewhere answered 404 for a logo it had just saved. Both
now use one folder (`src/utils/uploads.js`); logos saved before the fix show again. Settings →
Branding also checks the new file loads before saving it, and says why an upload failed.
- **Signing out didn't sign out of Accounts.** The navbar and bottom bar loaded the home page
straight after starting the sign-out call, which cancelled it. `logout()` now waits for it, then
goes to Accounts' sign-out (and back) itself.
### Changed
- **New demo data replaces the old demo people in Accounts too** (`set-demo`, `crosscode demo`,
the Hub's Load demo data): the last demo's people are removed there first (contracts 1.11.0
`people.removeDemo`, `src/accounts/move.ts removeDemoPeople`), then the new ones moved in.
## [3.2.0] - 2026-11-19
### Added
- **The heartbeat says what's on now** (`stats.live`, contracts 1.10.0, `hub/report.js liveNow`):
events with a session on now, or a one-day event (no sessions, at most 36 hours) on now, each give
or take 30 minutes, and tickets checked in during the last hour. Hub 2.7.0 asks for a second "yes"
before an emergency update takes a site with an event on down.
## [3.1.0] - 2026-11-19
Found after a church moved sign-in without email set up in Accounts: Accounts couldn't send codes or
password links, sign-in failed with a 500, and nobody could get in. Requires Accounts 1.2.0
(`— requires accounts 1.2.0`) and contracts 1.9.0.
### Added
- **Settings → Sign-in → Email and WhatsApp for the church's sign-in** (`src/accounts/messaging.ts`,
`components/admin/AccountsMessaging.tsx`): what Accounts can send, and this site's SMTP and WAWP
settings to copy into it. The password and access token never reach the page: left blank, this
site's own are used, sealed with the link's secret on the way. **Send a test** has Accounts send a
test email / WhatsApp with those settings (nothing saved); **Save in Accounts** tests again and
saves each part only if its test worked. Shown whenever Accounts is connected, so a church that
already moved can mend it. `GET /api/v2/settings/sign-in/messaging`, `POST …/messaging/test`,
`POST …/messaging`.
- **"Use this site's logo and colours"** on Settings → Sign-in (`POST /api/v2/settings/sign-in/look`):
the church's sign-in pages get this site's name, logo (made a full address) and colours
(`church.branding`); a move sends them too, filling only what Accounts doesn't have
(`src/accounts/look.ts`).
### Changed
- **The move needs Accounts' email.** Check reports what Accounts can send (and how many people get
WhatsApp codes, which go by email while Accounts' WhatsApp isn't set up); Move is disabled, and
refused by the server (`EMAIL_NOT_READY`), until Accounts' email works.
## [3.0.0] - 2026-11-19
Sign-in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md). Requires
+26 -15
View File
@@ -127,13 +127,17 @@ server {
access_log /var/log/nginx/hope-events.access.log hope_proxy;
# Visitors only reach this through the VPS over HTTPS, so tell the app so.
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
# For the backend locations below ("location /" sets its own).
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
@@ -147,7 +151,10 @@ server {
```
The VPS nginx/Caddy must redirect plain HTTP to HTTPS and pass the `Host` header through to frps
unchanged (frps picks the site by its host name). For nginx on the VPS, roughly:
unchanged (frps picks the site by its host name). Send every path through as it is: no
`location ~* \.(png|css|js…)$` caching rules for this site on the VPS, which would send
`/api/uploads/…/logo.png` to the site instead of the backend. (Since 3.6.1 the site passes such
requests on to the backend itself, but they're slower that way.) For nginx on the VPS, roughly:
```nginx
server {
@@ -188,13 +195,17 @@ server {
client_max_body_size 25m;
access_log /var/log/nginx/hope-events.access.log hope_proxy;
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
# For the backend locations below ("location /" sets its own).
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# The API and uploaded files go to the backend. Keep the ^~: without it, any regex location
# (e.g. one that caches *.png or *.css) wins and sends /api/uploads/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:5000; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:5000; }
location ~ ^/(api|uploads|health|docs)(/|$) { proxy_pass http://127.0.0.1:5000; }
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
+8 -3
View File
@@ -22,12 +22,17 @@ Events password until an admin moves sign-in (step 4). The plan behind it is
Site settings → **Sign-in**:
1. **Check the move.** Nothing changes. It lists how many people move, who already has a church
1. **Set up the church account's email** (Email and WhatsApp for the church's sign-in, on the same
page, from 3.1.0). Accounts sends sign-in codes and password links itself, so without email there
nobody could sign in after the move; Move stays disabled until it works. The page copies this
site's email settings (leave the password blank to use this site's), **Send a test email**, check
it arrived, then **Save in Accounts**. WhatsApp the same way, if you use it.
2. **Check the move.** Nothing changes. It lists how many people move, who already has a church
account (they're linked to it and keep that account's password), anyone who can't move and why,
and the guests and deleted people who stay in Cross Events only.
2. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
3. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
sign-in). By default every admin is ticked.
3. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
4. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
closes). It takes about a minute. People already signed in stay signed in.
What people notice afterwards:
+50
View File
@@ -12,6 +12,56 @@ 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.1
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
the site can't show it yet", depending on how the server is set up. Uploaded pictures, certificate
downloads and the like now show on those servers too.
## 3.6.0
- **People's details are checked every night.** Cross Events compares everyone's name, email,
phone and news choices with their church account and fixes any that are out of date, and handles
accounts that were deleted, in case a change never reached this site. You can see it, run it or
switch it off under Settings → Background jobs. It needs Accounts 1.5.0.
## 3.5.0
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
sign-in (Accounts). Demo data keeps it now, and a site that lost it connects again by itself
within about 15 minutes of updating.
- When signing in fails, Cross Code is told why, so it can help sooner.
## 3.4.0
- **Switch background jobs on and off yourself.** Settings → Background jobs has a switch for each
job (reminders, backups, the daily summary and so on) and lets you change when it runs, with ready
choices such as "every 15 minutes" or "daily at 07:00". It works straight away, no restart needed,
and one click puts a job back to how the server normally runs it.
- **Run now** works for a job that's switched off too, for when you want it once.
## 3.3.0
- **Fix:** a new logo or favicon sometimes didn't show after saving. It's saved and shown properly
now, and logos that went missing this way come back.
- **Fix:** signing out of this site now also signs you out of your church account.
- Loading new demo data replaces the old demo people in the church's Accounts too.
## 3.2.0
- Cross Code now sees when an event is on at your church before an urgent update, so it isn't taken
offline in the middle of your check-in without a good reason.
## 3.1.0 — requires accounts 1.2.0
- **Fix:** moving sign-in to your church's Accounts now needs Accounts' email to work first, so
people can always get their sign-in codes and password links. Settings → Sign-in shows whether it
does, and sets it up for you: it copies this site's email settings (your password stays where it
is), sends a test, and only saves them in Accounts once the test arrived. The same for WhatsApp.
- If your church already moved without it, the same page sets it up now.
- The church's sign-in page now has your logo and colours: they're taken from this site when you
move, and **Use this site's logo and colours** (Settings → Sign-in) updates them any time.
## 3.0.0 — requires accounts 1.1.0
- **One sign-in for all your church's sites and apps.** People can now sign in to Cross Events with
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.0.0",
"version": "3.6.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+18 -4
View File
@@ -76,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');
@@ -1888,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) {
@@ -1904,7 +1910,7 @@ async function main() {
}, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 });
clearScheduledEmails();
const pastFinancials = await closePastEvents();
const accounts = await demoAccounts();
const accounts = await demoAccounts(oldSubs);
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
@@ -1954,18 +1960,21 @@ async function main() {
for (const s of staffTeam) console.log(` ${s.role.padEnd(10)} ${s.email}`);
console.log(`Every other demo person also uses ${DEMO_PASSWORD}.`);
if (accounts) {
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
}
}
/**
* 3.0.0: with sign-in through the church's Accounts, the demo people are moved there too (with the
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). A demo person whose
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). 3.3.0: first, the last
* demo's people (`oldSubs`) are removed from Accounts (removeDemoPeople), so Accounts has the
* same people as the site. A demo person whose
* email already has an account from an earlier demo is linked to it. The compiled code (dist/) on a
* server; the TypeScript through tsx in development.
*/
let accountsDb = null;
async function demoAccounts() {
async function demoAccounts(oldSubs = []) {
const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js');
let move;
if (fs.existsSync(dist)) {
@@ -1978,7 +1987,12 @@ async function demoAccounts() {
const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } });
if (mode?.value !== 'accounts') return null;
try {
return await move.moveNewPeople(admin.accountId || null);
// Accounts before 1.3.0 doesn't know the request: the new demo still moves, the old stays.
const gone = await move.removeDemoPeople(oldSubs, admin.accountId || null).catch((e) => {
console.warn(`[warn] The last demo's people couldn't be removed from Accounts (${e.message}); they stay there until Accounts is updated to 1.3.0 and the demo is loaded again.`);
return { removed: 0 };
});
return { ...(await move.moveNewPeople(admin.accountId || null)), removed: gone.removed };
} catch (e) {
console.warn(`[warn] The demo people couldn't be moved to Accounts (${e.message}). Run the demo again once Accounts can be reached.`);
process.exitCode = 1;
@@ -7,12 +7,16 @@
import { connectTo } from '../links/connect';
import { linkedProducts } from '../links/store';
import { accountsLink } from './client';
import { getSetting, setSetting } from './mode';
import { getSetting, setSetting, viaAccounts } from './mode';
export const AUTO_KEY = 'accounts_auto_connected';
export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> {
if (await getSetting(AUTO_KEY)) return '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';
+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 };
}
+39 -9
View File
@@ -14,16 +14,17 @@
* 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, type ImportPerson, type ImportResult } from '@crosscode/contracts';
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> };
const { getSettingSync } = require('../utils/settingsCache') as { getSettingSync(k: string, f?: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export class MoveError extends Error {
@@ -143,11 +144,6 @@ export async function status(): Promise<MoveSummary> {
};
}
function church() {
const name = getSettingSync('org_name', '') || getSettingSync('site_name', '') || null;
const colour = getSettingSync('primary_color', '') || getSettingSync('brand_color', '');
return { name: name ? name.slice(0, 200) : null, primaryColour: /^#[0-9a-fA-F]{6}$/.test(colour) ? colour : null };
}
export type CheckResult = {
accountsVersion: string;
@@ -159,6 +155,8 @@ export type CheckResult = {
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() {
@@ -174,7 +172,7 @@ async function connected() {
/** 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: church() });
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');
}
@@ -199,9 +197,15 @@ export async function check(): Promise<CheckResult> {
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;
@@ -259,9 +263,35 @@ export async function moveNewPeople(actor: string | null = null): Promise<{ move
}
}
/**
* 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());
@@ -271,7 +301,7 @@ export async function move(opts: { actor: { id: string; role: string; name?: str
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: church(),
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');
@@ -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;
}
+9 -2
View File
@@ -20,6 +20,7 @@ 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');
@@ -144,7 +145,10 @@ async function startSignIn(req: Request, res: Response) {
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
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);
}
}
@@ -158,7 +162,8 @@ async function callback(req: Request, res: Response) {
let auth;
try {
auth = await accounts();
} catch {
} catch (e) {
await recordSignInError('ACCOUNTS_UNAVAILABLE', (e as Error).message);
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
@@ -168,8 +173,10 @@ async function callback(req: Request, res: Response) {
} 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);
@@ -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 };
}
+3 -10
View File
@@ -196,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);
+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 };
+166 -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,11 @@ 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.
@@ -117,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 {
@@ -208,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 };
}
/**
@@ -240,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' });
@@ -257,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)) {
@@ -295,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;
}
@@ -318,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);
@@ -330,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
@@ -356,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) || [],
};
@@ -368,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,
};
+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 };
@@ -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 });
@@ -5,6 +5,8 @@ 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');
@@ -94,6 +96,7 @@ export const signInCheck = defineRoute({
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) };
@@ -132,6 +135,120 @@ export const signInUndo = defineRoute({
},
});
// ─── 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() });
@@ -58,6 +58,7 @@ 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';
@@ -104,6 +105,10 @@ before(async () => {
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 });
@@ -143,6 +148,34 @@ async function signInThroughEvents(browser: Browser, email: string, password: st
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();
@@ -7,7 +7,9 @@ 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); },
}));
@@ -21,6 +23,7 @@ beforeEach(() => {
mockConnects.length = 0;
mockListed = [];
mockLink = null;
mockMode = 'local';
});
test('connects to the Accounts the Hub lists, as the system, once', async () => {
@@ -46,3 +49,13 @@ test('already connected by an admin: just remembers it', async () => {
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,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' });
});
@@ -0,0 +1,74 @@
// Branding uploads end to end (3.3.0): the real v2 upload routes (multer saving to disk) and the
// real file serving, as app.js mounts them. The logo and favicon saved are the files the returned
// address serves, wherever the backend was started from (before 3.3.0 a backend started outside
// backend/ answered 404 for a logo it had just saved). Only the database is a stand-in (no admin
// yet, so the upload is allowed as during setup).
import express from 'express';
import fs from 'fs';
import os from 'os';
import path from 'path';
import request from 'supertest';
import { v2Router } from '../src/v2';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { serveUploads } = require('../src/utils/uploads');
/* eslint-enable @typescript-eslint/no-require-imports */
function site() {
const app = express();
app.use(express.json());
app.use('/api/v2', v2Router());
app.use('/api/uploads', serveUploads());
return app;
}
// Any model, any call: nothing found, no users (as before setup).
jest.mock('../src/config/db', () => {
const anything: unknown = new Proxy(function () { /* callable */ }, {
get: (_t, key) => (key === 'then' ? undefined : key === 'count' ? async () => 0 : anything),
apply: async () => null,
});
return anything;
});
// The real upload folder of this checkout (as multer writes it), cleaned up after.
const BRANDING = path.join(__dirname, '..', 'public', 'uploads', 'branding');
const made: string[] = [];
afterAll(() => { for (const f of made) fs.rmSync(path.join(BRANDING, f), { force: true }); });
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
describe('branding uploads', () => {
const startedIn = process.cwd();
// PM2 or a script may start the backend from anywhere: the served files mustn't depend on it.
beforeAll(() => process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), 'events-cwd-'))));
afterAll(() => process.chdir(startedIn));
test.each([['logo', 'logo.png'], ['favicon', 'icon.png']])('a %s upload is served at the address it answers with', async (kind, name) => {
const app = site();
const up = await request(app).post(`/api/v2/uploads/${kind}`).attach('image', PNG, { filename: name, contentType: 'image/png' });
expect(up.status).toBe(200);
const saved = String(up.body.data.path);
expect(saved).toMatch(new RegExp(`^/uploads/branding/${kind}-[\\w-]+\\.png$`));
made.push(path.basename(saved));
expect(fs.existsSync(path.join(BRANDING, path.basename(saved)))).toBe(true);
const got = await request(app).get(new URL(up.body.data.url).pathname);
expect(got.status).toBe(200);
expect(Buffer.compare(got.body as Buffer, PNG)).toBe(0);
});
test('app.js serves uploads from that same folder, never one relative to where it started', () => {
const source = fs.readFileSync(path.join(__dirname, '..', 'src', 'app.js'), 'utf8');
expect(source).toContain("require('./utils/uploads').serveUploads()");
expect(source).not.toMatch(/express\.static\(\s*['"`]/);
});
test('a file that isn\'t an image is refused, and nothing is saved', async () => {
const app = site();
const before = fs.existsSync(BRANDING) ? fs.readdirSync(BRANDING).length : 0;
const up = await request(app).post('/api/v2/uploads/logo').attach('image', Buffer.from('<html>'), { filename: 'page.html', contentType: 'text/html' });
expect(up.status).toBe(400);
expect((fs.existsSync(BRANDING) ? fs.readdirSync(BRANDING).length : 0)).toBe(before);
});
});
+35
View File
@@ -36,6 +36,41 @@ describe('job registry', () => {
warn.mockRestore();
});
test('3.4.0: an admin choice wins over the env flag and schedule; JOBS_ENABLED=false still wins over everything', () => {
const { setOverridesForTest, envEnabled } = require('../src/jobs');
try {
delete process.env.JOBS_ENABLED;
process.env.WAITLIST_JOB_ENABLED = 'false';
process.env.JOB_SCHEDULE_WAITLIST = '*/5 * * * *';
setOverridesForTest({ waitlist: { enabled: true, cron: '*/20 * * * *' }, backup: { enabled: false } });
expect(envEnabled(job('waitlist'))).toBe(false);
expect(isEnabled(job('waitlist'))).toBe(true);
expect(cronFor(job('waitlist'))).toBe('*/20 * * * *');
expect(isEnabled(job('backup'))).toBe(false);
expect(isEnabled(job('temp-cleanup'))).toBe(true); // no env flag, no choice
process.env.JOBS_ENABLED = 'false';
expect(isEnabled(job('waitlist'))).toBe(false);
// A broken saved schedule falls back to the env's.
delete process.env.JOBS_ENABLED;
setOverridesForTest({ waitlist: { cron: 'nonsense' } });
expect(cronFor(job('waitlist'))).toBe('*/5 * * * *');
expect(isEnabled(job('waitlist'))).toBe(false); // the env flag again
} finally {
setOverridesForTest({});
}
});
test('3.4.0: setOverride checks its input before saving', async () => {
const { setOverride, isCron } = require('../src/jobs');
expect(isCron('*/10 * * * *')).toBe(true);
expect(isCron('0 7 * * *')).toBe(true);
expect(isCron('every day')).toBe(false);
expect(isCron('* * * * * *')).toBe(false); // seconds aren't offered
await expect(setOverride('nope', { enabled: true })).rejects.toMatchObject({ statusCode: 404 });
await expect(setOverride('waitlist', { enabled: 'yes' })).rejects.toMatchObject({ statusCode: 400 });
await expect(setOverride('waitlist', { cron: 'every day' })).rejects.toMatchObject({ statusCode: 400 });
});
test('daily jobs fire at local (Johannesburg) time', () => {
// 07:00 SAST = 05:00 UTC
const next = nextRun('0 7 * * *', new Date('2026-11-04T06:00:00Z'));
+37
View File
@@ -0,0 +1,37 @@
// 3.2.0: the heartbeat's `stats.live` (what's on now), which the Hub reads before an emergency
// update takes the site down. A session on now, or a one-day event without sessions, counts; a
// multi-week course with no session today doesn't.
const NOW = new Date('2026-11-22T09:00:00.000Z');
const H = 3600e3;
const mockSessions = [];
const mockEvents = [];
let mockCheckIns = 0;
jest.mock('../src/config/db', () => ({
eventSession: {
findMany: async ({ where }) => mockSessions.filter(s => s.cancelledAt === null && s.startsAt <= where.startsAt.lte && s.endsAt >= where.endsAt.gte).map(s => ({ eventId: s.eventId })),
},
event: {
findMany: async ({ where }) => mockEvents.filter(e => !e.hasSessions && e.startDate <= where.startDate.lte && e.endDate >= where.endDate.gte),
},
ticketUsage: { count: async () => mockCheckIns },
}));
const { liveNow } = require('../src/hub/report');
beforeEach(() => { mockSessions.length = 0; mockEvents.length = 0; mockCheckIns = 0; });
test('a session on now and a one-day event on now count; a long course and a later session don\'t', async () => {
mockSessions.push({ eventId: 'course', startsAt: new Date(NOW.getTime() - H), endsAt: new Date(NOW.getTime() + H), cancelledAt: null });
mockSessions.push({ eventId: 'later', startsAt: new Date(NOW.getTime() + 5 * H), endsAt: new Date(NOW.getTime() + 6 * H), cancelledAt: null });
mockSessions.push({ eventId: 'cancelled', startsAt: new Date(NOW.getTime() - H), endsAt: new Date(NOW.getTime() + H), cancelledAt: new Date() });
mockEvents.push({ id: 'breakfast', startDate: new Date(NOW.getTime() - H), endDate: new Date(NOW.getTime() + 2 * H) });
mockEvents.push({ id: 'term', startDate: new Date(NOW.getTime() - 20 * 24 * H), endDate: new Date(NOW.getTime() + 40 * 24 * H) });
mockCheckIns = 12;
expect(await liveNow(NOW)).toEqual({ eventsNow: 2, checkInsLastHour: 12 });
});
test('starting within half an hour counts as on', async () => {
mockEvents.push({ id: 'soon', startDate: new Date(NOW.getTime() + 20 * 60e3), endDate: new Date(NOW.getTime() + 3 * H) });
expect((await liveNow(NOW)).eventsNow).toBe(1);
});
+6
View File
@@ -108,6 +108,12 @@
"layer": "install",
"from": "https://{domain}",
"required": true
},
{
"name": "BACKEND_INTERNAL_URL",
"layer": "install",
"from": "http://127.0.0.1:{apiPort}",
"description": "The backend on this server: requests for /api or /uploads that reach the site are passed to it (3.6.1)"
}
]
}
+23 -4
View File
@@ -1,6 +1,15 @@
import type { NextConfig } from "next";
import { withSentryConfig } from "@sentry/nextjs";
// Requests for the backend (/api, /uploads) that reach the site anyway are passed to it (3.6.1).
// On a server nginx sends those paths to the backend, but a proxy in front can send some to the
// site instead: one with a rule for file extensions (static-file caching) sent every
// /api/uploads/…png here, so an uploaded logo never showed. BACKEND_INTERNAL_URL is the backend on
// this server (http://127.0.0.1:<port>), never the public address, which would come straight back
// here. The end-to-end tests set E2E_API_PROXY (3.0.0): the site and its API on one address, as
// nginx does, so Accounts' sign-in comes back to <site>/api/auth/callback.
const backend = (process.env.BACKEND_INTERNAL_URL || process.env.E2E_API_PROXY || "").replace(/\/+$/, "");
const nextConfig: NextConfig = {
// The end-to-end tests run their own dev server; a separate build folder keeps it
// from clashing with one already running.
@@ -12,10 +21,20 @@ const nextConfig: NextConfig = {
compiler: {
removeConsole: process.env.NODE_ENV === 'production',
},
// The end-to-end tests only (3.0.0): the site and its API on one address, as nginx does on a
// server, so Accounts' sign-in comes back to <site>/api/auth/callback. Unset everywhere else.
...(process.env.E2E_API_PROXY
? { async rewrites() { return [{ source: '/api/:path*', destination: `${process.env.E2E_API_PROXY}/api/:path*` }]; } }
...(backend
? {
// beforeFiles: ahead of every page, so a dynamic route like /[redirectUrl] never catches them.
async rewrites() {
return {
beforeFiles: [
{ source: '/api/:path*', destination: `${backend}/api/:path*` },
{ source: '/uploads/:path*', destination: `${backend}/uploads/:path*` },
],
afterFiles: [],
fallback: [],
};
},
}
: {}),
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.0.0",
"version": "3.6.1",
"private": true,
"scripts": {
"dev": "next dev",
@@ -240,24 +240,34 @@ function SiteSettingsPageInner() {
google_site_verification: googleVerificationCode(googleVerification),
});
// 3.3.0: an upload counts only once the site can show the file, so a setting never points at a
// file that isn't there (as it did when the backend served uploads from the wrong folder).
const uploadBrandingAsset = async (file: File, kind: "logo" | "favicon"): Promise<string> => {
const what = kind === "logo" ? "logo" : "favicon";
let path: string;
try {
return await uploadImage(token, kind, file);
} catch {
throw new Error(`${kind === "logo" ? "Logo" : "Favicon"} upload failed`);
path = await uploadImage(token, kind, file);
} catch (e) {
throw new Error(`The ${what} couldn't be uploaded: ${errorMessage(e) || "please try again"}.`);
}
const shown = await fetch(resolveToApiOrigin(path) || path, { cache: "no-store" }).then((r) => r.ok).catch(() => false);
if (!shown) throw new Error(`The ${what} was uploaded, but the site can't show it yet, so nothing was changed. Please try again; if it keeps happening, the server's uploads folder needs checking.`);
return path;
};
const saveBranding = async () => {
if (!token) return;
if (!token) {
setResult({ ok: false, message: "You've been signed out. Sign in again, then save." });
return;
}
setSaving(true);
setResult(null);
try {
let finalLogoUrl = logoUrl;
if (logoFile) finalLogoUrl = await uploadBrandingAsset(logoFile, "logo") || logoUrl;
if (logoFile) finalLogoUrl = await uploadBrandingAsset(logoFile, "logo");
let finalFaviconUrl = faviconUrl;
if (faviconFile) finalFaviconUrl = await uploadBrandingAsset(faviconFile, "favicon") || faviconUrl;
if (faviconFile) finalFaviconUrl = await uploadBrandingAsset(faviconFile, "favicon");
await apiV2Data("put", "/settings", {
authToken: token,
@@ -182,7 +182,7 @@ export default function PrivacyCentrePage() {
body: { type: "deletion", password: deletePassword, details: deleteReason || undefined },
}) as Promise<{ message?: string }>);
setDeleteMsg({ type: "ok", text: res?.message || "Your account is closed." });
setTimeout(() => logout(), 3000);
setTimeout(() => { void logout(); }, 3000);
} catch (e) {
setDeleteMsg({ type: "err", text: errorMessage(e) || "Could not send the request." });
} finally {
@@ -348,7 +348,7 @@ export default function UserProfilePage() {
}) as Promise<{ message?: string }>);
setCloseMsg({ type: "ok", text: res?.message || "Account closed." });
// Slight delay so the user can read the message, then log out
setTimeout(() => logout(), 2500);
setTimeout(() => { void logout(); }, 2500);
} catch (e) {
setCloseMsg({ type: "err", text: errorMessage(e) || "Failed to close account." });
} finally {
@@ -0,0 +1,145 @@
"use client";
import React, { useEffect, useState } from "react";
import { Mail, MessageCircle } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
type Overview = V2Result<"/settings/sign-in/messaging", "get">["data"];
type Answer = V2Result<"/settings/sign-in/messaging", "post">["data"];
type Result = { ok: boolean; error: string | null; saved: boolean } | null;
/**
* 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, so they're set up before sign-in moves there. This site's
* own settings are offered to copy (its password and WAWP token stay on the server: leave the field
* blank to use them), tested through Accounts, and saved there only once the test worked.
*/
export function AccountsMessaging({ onReady }: { onReady: (ready: { email: boolean; whatsapp: boolean }) => void }) {
const { token, user } = useAuth();
const [data, setData] = useState<Overview | null>(null);
const [err, setErr] = useState<string | null>(null);
const [email, setEmail] = useState({ host: "", port: "587", secure: false, user: "", from: "", pass: "", to: "" });
const [wa, setWa] = useState({ instanceId: "", accessToken: "", to: "" });
const [emailResult, setEmailResult] = useState<Result>(null);
const [waResult, setWaResult] = useState<Result>(null);
const [testedEmail, setTestedEmail] = useState<string | null>(null);
const [testedWa, setTestedWa] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const load = () => {
if (!token) return;
apiV2("get", "/settings/sign-in/messaging", { authToken: token })
.then(({ data: d }) => {
setData(d);
if (d.accounts) onReady({ email: d.accounts.email.ready, whatsapp: d.accounts.whatsapp.ready });
const e = d.events.email;
if (e) setEmail((x) => (x.host ? x : { ...x, host: e.host, port: String(e.port), secure: e.secure, user: e.user, from: e.from }));
if (d.events.whatsapp) setWa((x) => (x.instanceId ? x : { ...x, instanceId: d.events.whatsapp!.instanceId }));
})
.catch((e) => setErr(errorMessage(e) || "Could not load the email settings."));
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per sign-in
useEffect(load, [token]);
useEffect(() => {
setEmail((x) => (x.to ? x : { ...x, to: user?.email || "" }));
setWa((x) => (x.to ? x : { ...x, to: user?.phoneNumber || "" }));
}, [user]);
if (!token) return null;
if (!data) return err ? <p className="text-sm text-red-700">{err}</p> : <p className="text-sm text-gray-500">Loading email settings…</p>;
const emailKey = JSON.stringify({ ...email, to: undefined });
const waKey = JSON.stringify({ ...wa, to: undefined });
const emailBody = () => ({ email: { host: email.host, port: parseInt(email.port, 10) || 587, secure: email.secure, user: email.user, from: email.from, pass: email.pass || null, to: email.to } });
const waBody = () => ({ whatsapp: { instanceId: wa.instanceId, accessToken: wa.accessToken || null, to: wa.to } });
const run = async (key: string, save: boolean, body: object, after: (a: Answer) => void) => {
setBusy(key);
setErr(null);
try {
const { data: a } = save
? await apiV2("post", "/settings/sign-in/messaging", { authToken: token, body: body as never })
: await apiV2("post", "/settings/sign-in/messaging/test", { authToken: token, body: body as never });
after(a);
setData((d) => (d ? { ...d, accounts: { email: a.status.email, whatsapp: a.status.whatsapp }, accountsError: null } : d));
onReady({ email: a.status.email.ready, whatsapp: a.status.whatsapp.ready });
} catch (e) {
setErr(errorMessage(e) || "That didn't work.");
}
setBusy(null);
};
const acc = data.accounts;
const input = "w-full rounded-lg border px-3 py-2 text-sm";
const line = (r: Result, what: string) => r && (
<p className={`text-sm ${r.ok ? "text-green-800" : "text-red-800"}`} role="status">
{r.ok ? (r.saved ? `Saved in Accounts: ${what} works there now.` : `The test ${what} went. Check it arrived, then save.`) : `The test didn't work: ${r.error}`}
</p>
);
return (
<section className="border rounded-xl p-4 space-y-4">
<div>
<h3 className="font-medium">Email and WhatsApp for the church&apos;s sign-in</h3>
<p className="text-sm text-gray-600">Accounts sends sign-in codes and password links itself, with its own settings. Without email there, nobody can sign in after the move.</p>
</div>
{data.accountsError ? (
<p className="text-sm text-red-700">Accounts can&apos;t be reached: {data.accountsError}</p>
) : acc && (
<ul className="text-sm space-y-1">
<li className="flex items-center gap-2"><Mail className="h-4 w-4" aria-hidden /> Email: {acc.email.ready ? <span className="text-green-800">works{acc.email.from ? ` (from ${acc.email.from})` : ""}</span> : <span className="font-medium text-red-800">not set up</span>}</li>
<li className="flex items-center gap-2"><MessageCircle className="h-4 w-4" aria-hidden /> WhatsApp: {acc.whatsapp.ready ? <span className="text-green-800">works</span> : <span className="text-amber-800">not set up (WhatsApp codes then go by email)</span>}</li>
</ul>
)}
{err && <p className="text-sm text-red-800">{err}</p>}
<details open={!!acc && !acc.email.ready} className="rounded-lg border p-3">
<summary className="cursor-pointer text-sm font-medium">{acc?.email.ready ? "Change Accounts' email" : "Set up Accounts' email"}{data.events.email ? " (copied from this site)" : ""}</summary>
<div className="mt-3 grid gap-3 md:grid-cols-2">
<label className="text-sm">SMTP server<input className={input} value={email.host} onChange={(e) => setEmail({ ...email, host: e.target.value })} /></label>
<label className="text-sm">Port<input className={input} inputMode="numeric" value={email.port} onChange={(e) => setEmail({ ...email, port: e.target.value })} /></label>
<label className="text-sm">User name<input className={input} value={email.user} onChange={(e) => setEmail({ ...email, user: e.target.value })} autoComplete="off" /></label>
<label className="text-sm">Password<input className={input} type="password" value={email.pass} onChange={(e) => setEmail({ ...email, pass: e.target.value })} autoComplete="new-password" placeholder={data.events.email?.hasPass ? "Leave blank to use this site's password" : ""} /></label>
<label className="text-sm">Send from<input className={input} value={email.from} onChange={(e) => setEmail({ ...email, from: e.target.value })} /></label>
<label className="flex items-center gap-2 text-sm md:mt-6"><input type="checkbox" checked={email.secure} onChange={(e) => setEmail({ ...email, secure: e.target.checked })} /> TLS from the start (port 465)</label>
<label className="text-sm md:col-span-2">Send the test email to<input className={input} type="email" value={email.to} onChange={(e) => setEmail({ ...email, to: e.target.value })} /></label>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !email.host || !email.to}
onClick={() => run("email-test", false, emailBody(), (a) => { setEmailResult(a.email); if (a.email?.ok) setTestedEmail(emailKey); })}>
{busy === "email-test" ? "Sending…" : "Send a test email"}
</button>
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedEmail !== emailKey}
title={testedEmail !== emailKey ? "Send a test with these settings first" : undefined}
onClick={() => run("email-save", true, emailBody(), (a) => setEmailResult(a.email))}>
{busy === "email-save" ? "Saving…" : "Save in Accounts"}
</button>
</div>
<div className="mt-2">{line(emailResult, "email")}</div>
</details>
<details className="rounded-lg border p-3">
<summary className="cursor-pointer text-sm font-medium">{acc?.whatsapp.ready ? "Change Accounts' WhatsApp (WAWP)" : "Set up Accounts' WhatsApp (WAWP), optional"}{data.events.whatsapp ? " (copied from this site)" : ""}</summary>
<div className="mt-3 grid gap-3 md:grid-cols-2">
<label className="text-sm">WAWP instance id<input className={input} value={wa.instanceId} onChange={(e) => setWa({ ...wa, instanceId: e.target.value })} /></label>
<label className="text-sm">WAWP access token<input className={input} type="password" value={wa.accessToken} onChange={(e) => setWa({ ...wa, accessToken: e.target.value })} autoComplete="new-password" placeholder={data.events.whatsapp?.hasToken ? "Leave blank to use this site's token" : ""} /></label>
<label className="text-sm md:col-span-2">Send the test message to<input className={input} type="tel" value={wa.to} onChange={(e) => setWa({ ...wa, to: e.target.value })} placeholder="082 123 4567" /></label>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy || !wa.instanceId || !wa.to}
onClick={() => run("wa-test", false, waBody(), (a) => { setWaResult(a.whatsapp); if (a.whatsapp?.ok) setTestedWa(waKey); })}>
{busy === "wa-test" ? "Sending…" : "Send a test WhatsApp"}
</button>
<button type="button" className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50" disabled={!!busy || testedWa !== waKey}
title={testedWa !== waKey ? "Send a test with these settings first" : undefined}
onClick={() => run("wa-save", true, waBody(), (a) => setWaResult(a.whatsapp))}>
{busy === "wa-save" ? "Saving…" : "Save in Accounts"}
</button>
</div>
<div className="mt-2">{line(waResult, "WhatsApp")}</div>
</details>
</section>
);
}
@@ -1,16 +1,21 @@
"use client";
import React, { useCallback, useState } from "react";
import { Timer, Play, RefreshCw } from "lucide-react";
import { Timer, Play, RefreshCw, Pencil, RotateCcw } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
import { Switch } from "@/components/ui/switch";
type JobRun = { state: string; createdOn?: string; 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[] };
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobs: JobInfo[] };
type Override = { enabled: boolean | null; cron: string | null };
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: Override;
};
type JobsResponse = { mode: "queue" | "timers" | "off"; timezone: string; jobsEnabledEnv: boolean; jobs: JobInfo[] };
const STATE: Record<string, string> = {
completed: "bg-green-50 text-green-800",
@@ -21,12 +26,23 @@ const STATE: Record<string, string> = {
cancelled: "bg-gray-100 text-gray-500",
};
const PRESETS: { label: string; cron: string }[] = [
{ 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 * * *" },
];
const when = (d: string | null) => (d ? new Date(d).toLocaleString("en-GB", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "—");
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;
@@ -38,13 +54,16 @@ function outputText(run: JobRun): string {
try { return JSON.stringify(run.output); } catch { return ""; }
}
// Settings → Background jobs: what runs when, the last runs of each job, and "Run now".
// Settings → Background jobs: what runs when, the last runs of each job, "Run now", and (3.4.0)
// switching a job on or off and changing its schedule here, over what the server's .env says.
export function JobsTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [data, setData] = useState<JobsResponse | null>(null);
const [loading, setLoading] = useState(true);
const [running, setRunning] = useState<string | null>(null);
const [saving, setSaving] = useState<string | null>(null);
const [open, setOpen] = useState<string | null>(null);
const [editing, setEditing] = useState<{ name: string; cron: string } | null>(null);
const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(async () => {
@@ -75,6 +94,24 @@ export function JobsTab({ active }: { active: boolean }) {
}
};
/** Saves a choice for one job: a value wins over the .env, null goes back to it. */
const save = async (job: JobInfo, change: { enabled?: boolean | null; cron?: string | null }, done: string) => {
if (!token) return;
setSaving(job.name);
try {
await apiV2Data("put", "/admin/jobs/{name}", { params: { name: job.name }, authToken: token, body: change });
setMessage({ type: "ok", text: done });
setEditing(null);
await load();
} catch (e) {
setMessage({ type: "err", text: errorMessage(e) || "Couldn't save that" });
} finally {
setSaving(null);
}
};
const off = data?.mode === "off";
return (
<div className="space-y-4">
<div className="flex items-start justify-between gap-3">
@@ -82,6 +119,7 @@ export function JobsTab({ active }: { active: boolean }) {
<h2 className="text-lg font-semibold flex items-center gap-2"><Timer className="w-5 h-5 text-brand-600" /> Background jobs</h2>
<p className="text-sm text-gray-500 mt-0.5">
Tasks the server runs on a schedule ({data?.timezone || "local"} time). Each runs once per schedule, even with more than one server process, and failed runs are retried.
Switch a job on or off, or change when it runs: what you choose here wins over the server&apos;s .env and takes effect straight away.
</p>
</div>
<button type="button" onClick={load} disabled={loading} className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-50 shrink-0">
@@ -89,24 +127,37 @@ export function JobsTab({ active }: { active: boolean }) {
</button>
</div>
{message && <div className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{message && <div role="status" className={`p-3 border rounded text-sm ${message.type === "ok" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>}
{data?.mode === "timers" && (
<div className="p-3 border rounded bg-amber-50 text-amber-900 text-sm">The job queue couldn&apos;t start, so jobs are running on simple timers in this server process (no retries, history only since the last restart). Check the server log for &quot;[jobs]&quot;.</div>
)}
{data?.mode === "off" && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off (JOBS_ENABLED=false).</div>
{off && (
<div className="p-3 border rounded bg-gray-50 text-gray-700 text-sm">All background jobs are switched off in the server&apos;s .env (JOBS_ENABLED=false), so nothing here runs. Cross Code can change it from the Hub.</div>
)}
<ul className="divide-y border rounded-lg">
{(data?.jobs || []).map(job => {
const last = job.recent[0];
const busy = saving === job.name;
const enabledHere = job.override.enabled !== null;
const cronHere = job.override.cron !== null;
const isEditing = editing?.name === job.name;
return (
<li key={job.name} className="p-3">
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<Switch
checked={job.enabled}
disabled={busy || off}
onCheckedChange={(on) => save(job, { enabled: on }, `"${job.label}" is ${on ? "on" : "off"}.`)}
aria-label={`${job.label}: ${job.enabled ? "on" : "off"}`}
/>
<div className="min-w-0 mr-auto">
<div className="font-medium text-sm text-gray-900">{job.label}</div>
<div className={`font-medium text-sm ${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.envFlag ? ` (${job.envFlag}=false)` : ""}`}
{job.enabled ? `${describeCron(job.cron)} · next ${when(job.nextRun)}` : "Off"}
{enabledHere
? <> · {job.enabled ? "switched on" : "switched off"} here <button type="button" disabled={busy} className="underline hover:text-gray-700" onClick={() => save(job, { enabled: null }, `"${job.label}" follows the .env again (${job.envEnabled ? "on" : "off"}).`)}>use the .env ({job.envEnabled ? "on" : "off"})</button></>
: !job.envEnabled && job.envFlag ? ` (${job.envFlag}=false in the .env)` : ""}
</div>
</div>
{last && (
@@ -114,11 +165,43 @@ export function JobsTab({ active }: { active: boolean }) {
{last.state} · {when(last.completedOn || last.startedOn || last.createdOn || null)}
</button>
)}
<button type="button" disabled={running !== null || data?.mode === "off"} onClick={() => runNow(job)}
<button type="button" disabled={busy || isEditing} onClick={() => setEditing({ name: job.name, cron: job.cron })}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50">
<Pencil className="w-3.5 h-3.5" /> Schedule
</button>
<button type="button" disabled={running !== null || off} onClick={() => runNow(job)}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100 disabled:opacity-50">
<Play className="w-3.5 h-3.5" /> {running === job.name ? "Starting…" : "Run now"}
</button>
</div>
{isEditing && editing && (
<form className="mt-3 rounded border bg-gray-50 p-3 space-y-2" onSubmit={e => { e.preventDefault(); save(job, { cron: editing.cron.trim() }, `"${job.label}" now runs: ${describeCron(editing.cron.trim())}.`); }}>
<div className="flex flex-wrap gap-1.5">
{PRESETS.map(p => (
<button key={p.cron} type="button" onClick={() => setEditing({ name: job.name, cron: p.cron })}
className={`text-xs px-2 py-1 rounded border ${editing.cron === p.cron ? "bg-brand-50 border-brand-300 text-brand-800" : "bg-white hover:bg-gray-100"}`}>{p.label}</button>
))}
</div>
<div className="flex flex-wrap items-end gap-2">
<label className="text-xs text-gray-600">
Cron (minute hour day month weekday)
<input value={editing.cron} onChange={e => setEditing({ name: job.name, cron: e.target.value })} maxLength={100}
className="mt-1 block w-56 rounded border px-2 py-1 font-mono text-sm" aria-label="Cron schedule" />
</label>
<span className="text-xs text-gray-500 pb-1.5">{describeCron(editing.cron.trim())}</span>
<div className="ml-auto flex gap-2">
<button type="button" onClick={() => setEditing(null)} className="text-xs px-2.5 py-1.5 rounded border bg-white hover:bg-gray-100">Cancel</button>
<button type="submit" disabled={busy || !editing.cron.trim()} className="text-xs px-2.5 py-1.5 rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">{busy ? "Saving…" : "Save schedule"}</button>
</div>
</div>
<p className="text-xs text-gray-500">
The server&apos;s own schedule for this job is {describeCron(job.envCron)}{job.envCron !== job.defaultCron ? ` (set in the .env; normally ${describeCron(job.defaultCron)})` : ""}.
{cronHere && <> <button type="button" disabled={busy} className="inline-flex items-center gap-1 underline hover:text-gray-700" onClick={() => save(job, { cron: null }, `"${job.label}" is back on its own schedule.`)}><RotateCcw className="w-3 h-3" /> Use that again</button></>}
</p>
</form>
)}
{open === job.name && job.recent.length > 0 && (
<table className="mt-2 w-full text-xs">
<thead className="text-gray-500"><tr><th className="text-left font-medium py-1">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>
@@ -139,7 +222,7 @@ export function JobsTab({ active }: { active: boolean }) {
})}
{!loading && data && data.jobs.length === 0 && <li className="p-3 text-sm text-gray-500">No jobs.</li>}
</ul>
<p className="text-xs text-gray-400">Change a schedule with the env var JOB_SCHEDULE_&lt;NAME&gt; (cron, e.g. JOB_SCHEDULE_WAITLIST=&quot;*/5 * * * *&quot;), or switch one off with its own flag.</p>
<p className="text-xs text-gray-400">Without a choice here, the server&apos;s .env applies: each job&apos;s own flag (e.g. WAITLIST_JOB_ENABLED=false) and JOB_SCHEDULE_&lt;NAME&gt;.</p>
</div>
);
}
@@ -5,6 +5,7 @@ import { LogIn } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
import { AccountsMessaging } from "@/components/admin/AccountsMessaging";
type Status = V2Result<"/settings/sign-in", "get">["data"];
type Check = V2Result<"/settings/sign-in/check", "post">["data"];
@@ -26,6 +27,8 @@ export function SignInTab({ active }: { active: boolean }) {
const [keepAccountsNotices, setKeepAccountsNotices] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
// 3.1.0: what Accounts can send (the move needs its email).
const [sending, setSending] = useState<{ email: boolean; whatsapp: boolean } | null>(null);
useEffect(() => {
if (!active || !token) return;
@@ -98,6 +101,28 @@ export function SignInTab({ active }: { active: boolean }) {
{msg && <p className={`text-sm rounded-lg px-3 py-2 ${msg.ok ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`} role="status">{msg.text}</p>}
{status.accountsConnected && <AccountsMessaging onReady={setSending} />}
{status.accountsConnected && (
<section className="border rounded-xl p-4 flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-[16rem]">
<h3 className="font-medium">How the sign-in page looks</h3>
<p className="text-sm text-gray-600">The church&apos;s sign-in page uses its name, logo and colours. Moving sign-in copies this site&apos;s when it has none; this replaces them with this site&apos;s now.</p>
</div>
<button type="button" className="px-3 py-2 rounded-lg border text-sm" disabled={!!busy} onClick={async () => {
setBusy("look");
setMsg(null);
try {
await apiV2("post", "/settings/sign-in/look", auth);
setMsg({ ok: true, text: "The sign-in page now uses this site's logo and colours." });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
}
setBusy(null);
}}>{busy === "look" ? "Sending…" : "Use this site's logo and colours"}</button>
</section>
)}
{status.mode === "accounts" ? (
<section className="border rounded-xl p-4 space-y-3">
<p className="text-sm"><span className="font-medium">Through Accounts</span>{status.accountsUrl ? <> at <a className="underline" href={status.accountsUrl} target="_blank" rel="noreferrer">{status.accountsUrl.replace(/^https?:\/\//, "")}</a></> : null}{status.movedAt ? `, since ${when(status.movedAt)}` : ""}.</p>
@@ -158,7 +183,13 @@ export function SignInTab({ active }: { active: boolean }) {
<label className="flex items-center gap-2 text-sm py-0.5 text-gray-400"><input type="radio" name="notice" disabled checked={!keepAccountsNotices} readOnly /> Use Cross Events&apos; notice (remove Accounts&apos; notice in Accounts first)</label>
</fieldset>
)}
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
{!(sending?.email ?? checked.messaging.email) && (
<p className="text-sm font-medium text-red-800">Set up Accounts&apos; email above first (copy this site&apos;s, test it, save it): without it nobody could get a sign-in code or password link after the move.</p>
)}
{!!checked.messaging.whatsappTwoFactor && !(sending?.whatsapp ?? checked.messaging.whatsapp) && (
<p className="text-sm text-amber-800">{checked.messaging.whatsappTwoFactor} people get their codes by WhatsApp, which Accounts can&apos;t send yet: their codes will go by email until you set it up.</p>
)}
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices) || !(sending?.email ?? checked.messaging.email)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
{busy === "move" ? "Moving… (don't close this page)" : "Move sign-in to Accounts"}
</button>
<p className="text-xs text-gray-500">Pick a quiet time. It takes about a minute; people already signed in stay signed in. You can undo it for 14 days.</p>
@@ -5,7 +5,6 @@ import { usePathname } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { Home, Calendar, Phone, LogIn, UserPlus, LayoutDashboard, LogOut } from "lucide-react";
import { useBrandColorVar } from "@/lib/theme";
import { hardNavigate } from "@/lib/navigation";
export const BottomNav = () => {
const { user, loading: authLoading, logout } = useAuth();
@@ -15,8 +14,7 @@ export const BottomNav = () => {
const accentColor = useBrandColorVar("--brand-600");
const handleLogout = () => {
logout();
hardNavigate("/"); // a full load, so nothing of the old session stays in memory
void logout(); // signs out of Accounts too, then a full load of the next page
};
const isActive = (href: string) => {
@@ -9,7 +9,6 @@ import { BottomNav } from "./BottomNav";
import defaultLogo from "@/app/default_logo.png";
import { appName } from "@/lib/siteConfig";
import { resolveToApiOrigin } from "@/lib/api";
import { hardNavigate } from "@/lib/navigation";
type NavLink = {
href: string;
@@ -31,8 +30,7 @@ export const Navbar = () => {
};
const handleLogout = () => {
logout();
hardNavigate("/"); // a full load, so nothing of the old session stays in memory
void logout(); // signs out of Accounts too, then a full load of the next page
};
const navLinks: NavLink[] = [
@@ -23,7 +23,8 @@ export type AuthContextValue = {
verifyTwoFactor: (challengeId: string, code: string, rememberDevice: boolean) => Promise<AuthUser>;
resendTwoFactor: (challengeId: string) => Promise<TwoFactorChallenge>;
register: (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both"; newsOptIn?: boolean }) => Promise<void>;
logout: () => void;
/** Signs out here (and of Accounts, when sign-in goes through it), then leaves the page. */
logout: () => Promise<void>;
updateToken: (token: string) => void;
};
@@ -143,22 +144,28 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setUser(registeredUser);
}, []);
const logout = useCallback(() => {
const logout = useCallback(async () => {
const t = getToken();
clearToken();
cacheUser(null);
setToken(null);
setUser(null);
// 3.0.0: signed in through the church's Accounts, signing out here signs out there too (and of
// the church's other products), then comes back to this site's home page.
// the church's other products), then comes back to this site's home page. 3.3.0: this waits
// for that answer before leaving the page; before, callers loaded "/" straight away, which
// cancelled the call, so people stayed signed in to Accounts.
let next = "/";
if (t) {
fetchAuthMode()
.then((m) => (m === "accounts"
? fetch(`${API_BASE}/api/auth/signout`, { method: "POST", headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, body: "{}" }).then((r) => r.json())
: null))
.then((j: { data?: { url?: string | null } } | null) => { if (j?.data?.url) window.location.assign(j.data.url); })
.catch(() => { /* signed out here either way */ });
try {
if ((await fetchAuthMode()) === "accounts") {
const r = await fetch(`${API_BASE}/api/auth/signout`, { method: "POST", keepalive: true, headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, body: "{}" });
const j = (await r.json().catch(() => null)) as { data?: { url?: string | null } } | null;
if (j?.data?.url) next = j.data.url;
}
} catch { /* signed out here either way */ }
}
// A full load, so nothing of the old session stays in memory.
window.location.assign(new URL(next, window.location.origin).href);
}, []);
// Some endpoints (profile update, password change, session revocation) issue a
File diff suppressed because it is too large Load Diff
+498 -1
View File
@@ -6290,6 +6290,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/admin/jobs/{name}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* Switch a background job on or off, or change its schedule
* @description **Who:** Admins only.
*/
put: operations["putAdminJobsName"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/admin/jobs/{name}/run": {
parameters: {
query?: never;
@@ -7606,6 +7626,76 @@ export interface paths {
patch?: never;
trace?: never;
};
"/settings/sign-in/messaging": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Email and WhatsApp: this site's, and what Accounts can send
* @description **Who:** Admins only.
*/
get: operations["getSettingsSign-inMessaging"];
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postSettingsSign-inMessaging"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/settings/sign-in/messaging/test": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postSettingsSign-inMessagingTest"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/settings/sign-in/look": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postSettingsSign-inLook"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}/account/reset-two-factor": {
parameters: {
query?: never;
@@ -35048,15 +35138,28 @@ export interface operations {
content: {
"application/json": {
data: {
/** @description on, off or timers */
/** @description queue, timers or off */
mode: string;
timezone: string;
/** @description JOBS_ENABLED in the .env */
jobsEnabledEnv: boolean;
jobs: ({
name: string;
label: string;
cron?: string | null;
enabled: boolean;
envFlag?: string | null;
/** @description What the .env says */
envEnabled: boolean;
envCron: string;
defaultCron: string;
/** @description What an admin chose over the .env (null: the .env applies) */
override: {
enabled: boolean | null;
cron?: string | null;
} & {
[key: string]: unknown;
};
nextRun?: string | null;
/** @description Recent runs */
recent: {
@@ -35091,6 +35194,86 @@ export interface operations {
};
};
};
putAdminJobsName: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The name */
name: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description true or false wins over the .env; null goes back to it */
enabled?: boolean | null;
/** @description A cron schedule (five fields) that wins over the .env; null or empty goes back to it */
cron?: string | null;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
name: string;
override: {
enabled: boolean | null;
cron?: string | null;
} & {
[key: string]: unknown;
};
} & {
[key: string]: unknown;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postAdminJobsNameRun: {
parameters: {
query?: never;
@@ -39892,6 +40075,12 @@ export interface operations {
eventsVersions: number[];
} | null;
withTwoFactor: number;
/** @description 3.1.0: what Accounts can send; the move needs email */
messaging: {
email: boolean;
whatsapp: boolean;
whatsappTwoFactor: number;
};
};
};
};
@@ -40044,6 +40233,314 @@ export interface operations {
};
};
};
"getSettingsSign-inMessaging": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @description This site's own settings, to copy (never the password or token) */
events: {
email: {
host: string;
port: number;
secure: boolean;
user: string;
from: string;
hasPass: boolean;
} | null;
whatsapp: {
instanceId: string;
hasToken: boolean;
} | null;
};
/** @description What the church's Accounts can send (null: it can't be reached) */
accounts: {
email: {
ready: boolean;
host: string | null;
from: string | null;
};
whatsapp: {
ready: boolean;
instanceId: string | null;
};
} | null;
accountsError: string | null;
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postSettingsSign-inMessaging": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
email?: {
host: string;
port: number;
secure: boolean;
user: string;
from: string;
/** @description Blank: this site's own password */
pass?: string | null;
/**
* Format: email
* @description Where the test email goes
*/
to: string;
};
whatsapp?: {
instanceId: string;
/** @description Blank: this site's own token */
accessToken?: string | null;
/** @description The phone the test message goes to */
to: string;
};
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
email: {
ok: boolean;
error: string | null;
saved: boolean;
} | null;
whatsapp: {
ok: boolean;
error: string | null;
saved: boolean;
} | null;
status: {
email: {
ready: boolean;
host: string | null;
from: string | null;
};
whatsapp: {
ready: boolean;
instanceId: string | null;
};
};
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postSettingsSign-inMessagingTest": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
email?: {
host: string;
port: number;
secure: boolean;
user: string;
from: string;
/** @description Blank: this site's own password */
pass?: string | null;
/**
* Format: email
* @description Where the test email goes
*/
to: string;
};
whatsapp?: {
instanceId: string;
/** @description Blank: this site's own token */
accessToken?: string | null;
/** @description The phone the test message goes to */
to: string;
};
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
email: {
ok: boolean;
error: string | null;
saved: boolean;
} | null;
whatsapp: {
ok: boolean;
error: string | null;
saved: boolean;
} | null;
status: {
email: {
ready: boolean;
host: string | null;
from: string | null;
};
whatsapp: {
ready: boolean;
instanceId: string | null;
};
};
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postSettingsSign-inLook": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
name: string | null;
logoUrl: string | null;
primaryColour: string | null;
accentColour: string | null;
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postUsersIdAccountReset-two-factor": {
parameters: {
query?: never;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.0.0",
"version": "3.6.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+11 -8
View File
@@ -116,7 +116,7 @@ else
echo " backend/.env exists — kept"
fi
if [ ! -f "$DIR/frontend/.env.production" ]; then
echo "NEXT_PUBLIC_API_URL=$SITE_URL" > "$DIR/frontend/.env.production"
printf 'NEXT_PUBLIC_API_URL=%s\nBACKEND_INTERNAL_URL=http://127.0.0.1:%s\n' "$SITE_URL" "$API_PORT" > "$DIR/frontend/.env.production"
fi
if [ ! -f "$DIR/ecosystem.config.js" ]; then
sed -e "s/'hope-events-backend'/'$NAME-backend'/" -e "s/'hope-events-frontend'/'$NAME-frontend'/" -e "s/-p 3000/-p $WEB_PORT/" \
@@ -140,14 +140,17 @@ server {
server_name $DOMAIN;
client_max_body_size 25m;
# For the backend locations below ("location /" sets its own).
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
# The API, uploaded files, health and API docs go to the backend; everything else to the site.
location ~ ^/(api|uploads|health|docs)(/|\$) {
proxy_pass http://127.0.0.1:$API_PORT;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
# ^~ so a regex location added later (e.g. caching *.png) can't send /api/…/logo.png to the site.
location ^~ /api/ { proxy_pass http://127.0.0.1:$API_PORT; }
location ^~ /uploads/ { proxy_pass http://127.0.0.1:$API_PORT; }
location ~ ^/(api|uploads|health|docs)(/|\$) { proxy_pass http://127.0.0.1:$API_PORT; }
location / {
proxy_pass http://127.0.0.1:$WEB_PORT;
proxy_http_version 1.1;
+7
View File
@@ -464,6 +464,13 @@ only for a connected product:
logout, `user.updated`, Undo) against the whole Accounts app on real ports, each with an in-memory
database (14 tests, including demo people and moving again after Undo). `user.export` and `user.deleted` are Jest tests (`tests/accountsCalls.test.ts`).
13. **3.1.0 (after the first church moved):** Accounts has its own email and WhatsApp settings,
which a move doesn't bring, and it failed with a 500 when a code couldn't be sent, so nobody
could sign in. Now the move needs Accounts' email; Settings → Sign-in copies Events' SMTP / WAWP
into Accounts (secrets sealed, never on the page), with a test first (`messaging.*`, contracts
1.9.0); Accounts 1.2.0 shows a message instead of a 500 and sends WhatsApp codes by email when
WhatsApp is down.
## Decisions
Confirmed by Joshua on 2026-11-19, all as proposed.
+74 -11
View File
@@ -1,6 +1,6 @@
# Handover — Cross Code, all products
Last updated: 2026-11-19. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
Last updated: 2026-11-20. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
decisions table near the end). This file says where each phase stands and what comes next.
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
@@ -33,20 +33,70 @@ every release).
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Released** 2026-11-18 (`events@2.4.0`, `contracts@1.4.0`, Hub `v2.2.0`, crosscode-site `v1.4.0`; [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). **Before any church gets it:** the Events e2e run on Postgres and the VM test (EVENTS-2.4-PLAN §8) |
| 3 | Accounts 1.0.0 (+ contracts 1.5.0, agent 1.1.0, Hub 2.3.0) | **Released** 2026-11-18 (`accounts@1.0.0`, `contracts@1.5.0`, `agent@1.1.0`, Hub `v2.3.0`, crosscode-site `v1.5.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)). 37 backend and 8 Playwright tests pass without Postgres. **Before installing it for a church:** the VM test and a run on real Postgres; a Hub release source for `accounts@` tags |
| 4 | Cross Events 3.0.0: sign-in through Accounts, users migrated with their password hashes and 2FA | **Released** 2026-11-19 (`events@3.0.0`, `accounts@1.1.0`, `contracts@1.8.0`, Hub `v2.5.0`, crosscode-site `v1.6.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Tested on Postgres 18: both migrations, `test:accounts` on real databases (14/14), the Events e2e suite (111, incl. `sign-in-accounts.spec.ts`). **Not VM tested yet.** Roll out: Hub 2.5.0 deployed first, then per church Accounts 1.1.0 → Events 3.0 → Move (MIGRATING-TO-3.md); crosscode-site 1.6.0 once the first church has moved |
| 4+ | Running it: jobs from the dashboard, styled Accounts emails, .env from the Hub, sign-in health, the nightly people check | **Released** 2026-11-20 (see below). Unit, bats and full `npm run check` passing; **not VM tested, not deployed** |
| 5–7 | Website 1.0.0 → App 1.0.0 → App 1.x | Not started |
## Released 2026-11-20
All tagged and pushed; nothing deployed yet. Details in [CHANGELOG.md](../CHANGELOG.md), the apps' CHANGELOGs
and What's New, and [VERSIONS.md](./VERSIONS.md).
| Release | What |
|---------|------|
| `events@3.4.0`, `accounts@1.4.0`, `contracts@1.12.0`, `agent@1.3.0`, Hub `v2.8.0` | Background jobs switched on/off and rescheduled from each site's admin (saved in `job_overrides`, wins over the .env, applies at once; Accounts gets an Admin → Background jobs page). Accounts' emails styled as Events' (`src/lib/emails.ts`). The Hub reads and changes an install's .env (`env-read` / `env-set` jobs → `crosscode env`; secrets never leave the server; the file is put back if the site doesn't start; the frontend's file triggers a rebuild) |
| `events@3.5.0`, `contracts@1.13.0`, `agent@1.3.1`, Hub `v2.9.0` | **Fix:** "Load demo data" deleted the Accounts link (`set-demo.js` truncated `ProductLink`), so events-demo couldn't sign anyone in (`ACCOUNTS_UNAVAILABLE`). Demo data keeps the link; a site in Accounts mode without a link reconnects at its next heartbeat. Heartbeat `stats.signIn`; Hub alerts: not linked (critical), wrong Accounts, sign-in failing, an Accounts nothing links to. **Agent 1.3.0 reported itself as 1.2.0**: use 1.3.1 |
| `accounts@1.6.0` | A "New sign-in" email (and WhatsApp) after every sign-in; Sign-in settings → `signin_notices` turns it off |
| `events@3.6.1` | **Fix:** logo/favicon uploads failed on events-demo ("uploaded, but the site can't show it yet"). FastPanel's static-file rule sent every `/api/…` path with a file extension (`.png`, `.pdf`, …) to the frontend. The site now passes `/api/*` and `/uploads/*` on to the backend (`BACKEND_INTERNAL_URL`); the installers' nginx uses `location ^~`. Change each FastPanel site too (below) |
| `events@3.6.0`, `accounts@1.5.0`, `contracts@1.14.0` | The nightly people check (`accounts-people-check`, 04:30): `people.check` 500 subs at a time; fixes out-of-date copies, handles deleted accounts as `user.deleted`, stops (changing nothing) when most people are unknown. Skipped with an Accounts before 1.5.0 |
**To fix events-demo before it's updated:** its Settings → Linked products → Connect the church's
Accounts (or update it to Events 3.5.0+, which reconnects within ~15 minutes).
## FastPanel sites (central server)
FastPanel's nginx on the central server is the only router for sites behind frp: the church
server has no nginx. Its static-file handling adds a regex location for file extensions
(`png|jpg|ico|svg|css|js|pdf|txt|…`) that falls back to the site's main proxy, the frontend. A
plain `location /api` loses to it, so `/api/uploads/…/logo.png` reached Next.js and got a 404
(fixed in the site by Events 3.6.1, but slower and without the visitor's IP). In each Events
site's nginx config in FastPanel, the backend locations must be `^~` (a prefix match that no
regex can override):
```nginx
location ^~ /api/ {
proxy_pass http://127.0.0.1:<api port>;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location = /api { proxy_pass http://127.0.0.1:<api port>; }
```
The Hub's FastPanel email (AGENT-1.0-PLAN §11) still says just "/api → backend": it should say
`location ^~ /api/`. Check after a change:
`curl -sI https://<domain>/api/health.png` must say `X-Powered-By: Express` (a 404 is fine).
## Next up
1. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) (with the latest patch
releases: Hub 2.1.1, agent 1.0.1, Events 2.3.1): Hub 2.1 (make and back up
the job-signing key first) → the central server's agent (check `proxy_bind_addr = 127.0.0.1`)
→ each church server's agent → **adopt** the demo site, then each church (Link existing → Move
onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure).
3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
4. **Cross Events 2.4.0** (phase 2) is built on branches: run `npm run test:e2e` in `apps/events`
(with the e2e Postgres) and the VM test in EVENTS-2.4-PLAN §8, then merge and release in its
order (contracts 1.4.0 → Hub 2.2.0, deployed → Events 2.4.0 → crosscode-site 1.4.0).
Nothing from phase 1 onwards is rolled out yet (VERSIONS.md, "Deployed / rolled out"), so roll out
straight to the latest releases rather than each one in turn.
1. **VM test the latest releases** before any church gets them (the 2026-11-17 VM test covered
Events 2.2 and agent 1.0; Events 2.4+, Accounts and Events 3.x haven't been on it): Events 3.x
with Accounts and the move (MIGRATING-TO-3.md), the event feed and Linked products
(EVENTS-2.4-PLAN §8), and today's: the Hub's .env panel (read; a backend URL with restart; a
frontend value with rebuild; a value that stops the site, so it's put back), the job switches,
a demo load (the Accounts link stays) and the people check. Also the Events e2e suite on Postgres.
2. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md), with the latest releases:
**Hub 2.9.0** (make and back up the job-signing key first; 2.4.0 onwards have migrations) → the
central server's agent (check `proxy_bind_addr = 127.0.0.1`) → each church server's agent
(**1.3.1**, never 1.3.0) → **adopt** the demo site, then each church (Link existing → Move onto the
monorepo) → per church **Accounts 1.5.0 before Events 3.6.0**, then the move to Accounts
(MIGRATING-TO-3.md) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
3. **Deploy crosscode-site.** `v1.3.0`–`v1.5.0` are tagged but not recorded as deployed;
`v1.6.0` (one sign-in through Accounts) once the first church has moved.
4. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
## The VM test (2026-11-17)
@@ -95,6 +145,19 @@ rollout.
- **AI for a church:** set the licence's monthly AI cap above R0 on the Hub; with no cap the
buttons don't show (rules in Events' handover, "AI rules"). Churches see tokens; only the Hub
shows rand (markup 15% by default).
- **The agent's version is in two places:** `apps/agent/package.json` *and* `AGENT_VERSION` in
`apps/agent/src/stats.ts` (what it reports to the Hub). Bump both; the agent's test checks they match,
so run `npm run check` *after* the bump (1.3.0 shipped reporting 1.2.0).
- **Background jobs:** each job's switch and schedule can be set in the site's admin (Events and
Accounts, AppSetting `job_overrides`); that wins over the .env flag and `JOB_SCHEDULE_<NAME>`.
`JOBS_ENABLED=false` still turns everything off. A new job gets a `label` and, if it may be turned
off from the .env, an `env` flag.
- **An install's .env from the Hub** (install page → Settings (.env), agent 1.3.0+): plain values
only. Names matching `SECRET_ENV_NAME` (contracts) / `SECRET_NAME` (`scripts/lib/envedit.cjs`;
keep them in step) and generated values can't be read or changed from the Hub. Changing an
address there doesn't change the Hub's domain for the install or FastPanel.
- **Demo data keeps the links** to the church's other products (`KEEP_TABLES` in
`apps/events/backend/scripts/set-demo.js`). Anything that must survive a demo load goes there.
- **Releasing:** branch → merge → tag (`<product>@<version>` here, `v<version>` in events-hub and
crosscode-site) → push, with a CHANGELOG entry, and `npm run check` first. Pushes to c-git often
fail authentication the first time; retry once. A push can also hang waiting on a login prompt
+2 -1
View File
@@ -843,7 +843,7 @@ ranking.
| 27 | Deploying from the Hub | A **server agent** on every server runs installs, updates and uninstalls on **signed jobs of fixed types** from the Hub, always through the `crosscode` script (which still works by hand). Changes decisions 10 and 23; rule 2 (§1) reworded |
| 28 | The agent's exposure | **It has no URL or listening port.** It only polls the Hub over outgoing HTTPS |
| 29 | Confirming risky jobs | Uninstall and emergency updates need **2FA again** in the Hub; uninstall also needs the short name typed |
| 30 | Notice before updates | **Scheduled: at least 4 hours**; **emergency: at least 15 minutes**, with a reason. The site admin gets an email and a banner straight away. Joshua picks the time. A job the agent misses doesn't run late |
| 30 | Notice before updates | **Scheduled: at least 4 hours**; **emergency: at least 15 minutes**, with a reason. The site admin gets an email and a banner straight away. Joshua picks the time. A job the agent misses doesn't run late. **Changed 2026-11-19** (decision 39): an emergency can also run as soon as possible |
| 31 | Uninstall | The church gets a **JSON export in our own format** (`crosscode.church-export/1`, no internal tables or ids), encrypted so the Hub can't read it, downloadable for **30 days**. The final backup is kept 30 days, then deleted (Joshua emailed 3 days before) |
| 32 | frp | Every church server is behind frp to **one central FastPanel server**. The Hub keeps the **port list** (unique across servers, same number local and remote), tunnels are named `<church>-<product>-web/-api` |
| 33 | frpc.ini | **Only appended to**, in marked blocks, checked with `frpc verify`, with a backup first; uninstall removes only its own block. `admin_addr = 127.0.0.1` / `admin_port = 7400` added once to `[common]` so frpc reloads without dropping other sites |
@@ -857,6 +857,7 @@ ranking.
| # | Question | Decision |
|---|----------|----------|
| 38 | Order after Accounts | **Cross Events 3.0.0 (sign-in through Accounts) is phase 4, the Church Website phase 5** (swapped). Events is what churches use today, so Accounts is proven on real users and their migrated passwords and 2FA first; the Website then starts with a church whose people already have accounts |
| 39 | Emergency updates now | An emergency update (reason and 2FA, as before) can run **as soon as possible**, at the agent's next poll (within a minute), as well as at a time at least 15 minutes away. The church is told it's happening now. When the church's Events heartbeat shows an event on now (a session or a one-day event, or check-ins in the last hour), the Hub names it and needs a second "yes". Hub 2.7.0, Events 3.2.0 |
## Still open
+58 -7
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-19. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-20. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -10,13 +10,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.0.0** | `events@3.0.0` | 2026-11-19 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.1.0** | `accounts@1.1.0` | 2026-11-19 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.2.0** | `agent@1.2.0` | 2026-11-19 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.8.0** | `contracts@1.8.0` | 2026-11-19 |
| Cross Code Hub | `events-hub` | **2.5.0** | `v2.5.0` | 2026-11-19 |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.6.1** | `events@3.6.1` | 2026-11-20 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.6.0** | `accounts@1.6.0` | 2026-11-20 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.3.1** | `agent@1.3.1` | 2026-11-20 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.14.0** | `contracts@1.14.0` | 2026-11-20 |
| Cross Code Hub | `events-hub` | **2.9.0** | `v2.9.0` | 2026-11-20 |
| crosscode.co.za | `crosscode-site` | **1.6.0** | `v1.6.0` | 2026-11-19 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-19 (last change) |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-20 (last change: nginx `location ^~ /api/`) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
on each run, so merging to `main` and pushing releases it. Its changes are listed in
@@ -37,6 +37,57 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Events 3.6.1 (fix):** logo and favicon uploads failed on events-demo: FastPanel's static-file
rule sent every `/api/…` path with a file extension to the frontend. The site now passes those on
to the backend. Also change the FastPanel site (HANDOVER.md, "FastPanel sites"). No migration.
- **Accounts 1.6.0:** a "New sign-in" email (and WhatsApp) after every sign-in, as Cross Events'
own sign-in sends; admins can turn it off. No migration.
- **Events 3.6.0 + Accounts 1.5.0 + contracts 1.14.0:** a nightly people check (Events asks Accounts
about everyone with an account, 500 at a time, `people.check`): out-of-date copies are fixed,
deleted accounts handled as `user.deleted`, and it stops if most people are unknown. Update
Accounts first (Events skips the check with an older one). No migrations; the Hub is unchanged.
- **Events 3.5.0 + contracts 1.13.0 + agent 1.3.1 + Hub 2.9.0:** loading demo data no longer deletes
the Accounts link (on events-demo nobody could sign in); a site in Accounts mode without a link
reconnects at its next heartbeat; the heartbeat says how the site signs in and the last failure,
and the Hub alerts when it isn't linked, is linked wrongly or sign-ins fail. **Agent 1.3.0
reported itself as 1.2.0**, so the Hub refused its .env jobs: install 1.3.1. No migrations.
- **Events 3.4.0 + Accounts 1.4.0 + contracts 1.12.0 + agent 1.3.0 + Hub 2.8.0:** background jobs
switched on and off (and rescheduled) from each site's admin, over the .env (saved in the
database, no migration); Accounts' emails styled as Cross Events'; the Hub shows an install's
.env (secrets only as set or not) and changes plain values with a restart or frontend rebuild
(`env-read` / `env-set` jobs, `crosscode env`; the file is put back if the site doesn't start).
The Hub's .env panel needs agent 1.3.0 on the server. No migrations.
- **Events 3.3.0 + Accounts 1.3.0 + contracts 1.11.0:** Accounts' pages in Cross Events' layout
(sidebar, a page per section), quick links to the church's sites, nightly backups (Admin →
Backups; needs `pg_dump` on the server), a fuller built-in privacy notice, a fixed favicon.
Events: signing out also signs out of Accounts; uploaded logos and favicons are served from the
folder they're saved in (they 404'd when the backend started elsewhere); new demo data removes
the old demo people from Accounts (`people.removeDemo`, needs Accounts 1.3.0). No migrations.
The Hub doesn't need contracts 1.11.0 (only Events and Accounts use the new request).
- **Hub 2.7.1:** a double click can't plan an update twice (buttons are off until the Hub answers,
and a second update for an install with one planned or running is refused). No migration.
- **Hub 2.7.0:** emergency updates "as soon as possible" (the agent's next poll), and a second "yes"
when the church has an event on now (from Events 3.2.0's heartbeat). 2.6.1: the Failed jobs filter
and alert search answered 500. No migration; deploy it.
- **Events 3.2.0 + contracts 1.10.0:** the heartbeat says what's on now (`stats.live`).
- **Events 3.1.0 + Accounts 1.2.0 + contracts 1.9.0:** the move to Accounts needs Accounts' email
(Settings → Sign-in sets it up by copying Events' SMTP / WAWP, tests, then saves); Accounts shows a
message instead of a 500 when a code can't be sent. **Use these instead of 3.0.0 / 1.1.0.**
- **Hub 2.6.0:** paged lists (jobs, audit log and alerts on the server), job filters for every
status, updates for one product at a time with that product's releases, an Events update that
keeps (or updates, or first installs) the church's Accounts explicitly, and installs found on a
server tied to their registration. No migration. **Deploy it** (after 2.5.0, or straight to it).
- **`crosscode` script (2026-11-19, later):** Accounts' own `ecosystem.config.cjs` no longer stops
a deploy as "changed by hand".
- **Events 3.0.0** (phase 4, [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)): sign-in through the
church's Accounts. Needs Accounts 1.1.0 (`requires accounts 1.1.0`). Nothing changes for a
church until an admin moves sign-in (Settings → Sign-in); see `apps/events/MIGRATING-TO-3.md`.
+7 -6
View File
@@ -46,7 +46,7 @@
},
"apps/accounts/backend": {
"name": "@crosscode/accounts-backend",
"version": "1.1.0",
"version": "1.6.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
@@ -54,6 +54,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",
@@ -82,7 +83,7 @@
},
"apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend",
"version": "1.1.0",
"version": "1.6.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
@@ -108,7 +109,7 @@
},
"apps/agent": {
"name": "@crosscode/agent",
"version": "1.2.0",
"version": "1.3.1",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*",
@@ -127,7 +128,7 @@
},
"apps/events/backend": {
"name": "@crosscode/events-backend",
"version": "3.0.0",
"version": "3.6.1",
"hasInstallScript": true,
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
@@ -177,7 +178,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "3.0.0",
"version": "3.6.1",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -21275,7 +21276,7 @@
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.8.0",
"version": "1.14.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"

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