Compare commits

...
Author SHA1 Message Date
joshua 06222fd94a Merge branch 'fix/agent-stats-during-jobs' 2026-11-18 19:03:20 +02:00
joshuaandClaude Opus 5.5 43189c599a Release agent@1.1.1: stats during jobs, its real version
Stats go every minute on their own timer, also while a job runs (before,
a 30-minute install made the Hub alert that the server was down). The
version constant said 1.0.1 in 1.1.0; a test keeps it equal to
package.json now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:03:19 +02:00
joshua 2aab5918f7 Merge branch 'feat/accounts-1.0' 2026-11-18 15:23:06 +02:00
joshuaandClaude Opus 5.5 21c60ac99e Release events@2.4.0, accounts@1.0.0, contracts@1.5.0 and agent@1.1.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:23:06 +02:00
joshuaandClaude Opus 5.5 1318ba38bd docs: Accounts plan, handover and changelog after the install work and Playwright run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:02:21 +02:00
joshuaandClaude Opus 5.5 fdd53ae4db Accounts: Playwright on the real pages; interaction cookie path fix
The interaction address is now /api/v2/interaction/<uid> (redirecting to
the sign-in page): oidc-provider scopes its cookie to that path, so every
step's API call gets it. Before, a real browser never sent it and every
sign-in 'expired'; the test browser now honours cookie paths too.
8 Playwright tests (deep link, wrong password, foreign return address,
sign-up, reset mid-sign-in, 2FA set-up, account page, admin) on the real
backend with an in-memory database, no Postgres needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:01:32 +02:00
joshuaandClaude Opus 5.5 e1c6a4cce1 crosscode: install and add Accounts; agent: Accounts installs and add-product
crosscode install takes --products accounts (one product per install);
crosscode add <church> <product> installs a product next to a church's
others, as its app user, undoing only its own folder, database, PM2 and
site if a step fails. install_events/install_accounts share the checks,
ports and nginx site. Agent 1.1.0: install jobs for Accounts, and
add-product jobs (behind frp, with the Hub's ports and release).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:31:36 +02:00
joshuaandClaude Opus 5.5 7f34e184e1 Accounts: deploy hooks, env template, export, docs
scripts/products/accounts.sh (backup with pg_dump, build with the shared
packages, PM2, export, keep, failed-migration recovery); accounts in
SUPPORTED_PRODUCTS so deploy updates it where a church has it. Env
template in both places, PM2 example, export script, /api/health
version from package.json. README, CHANGELOG, WHATS-NEW; the plan's
changes while building and what's still to do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:18:40 +02:00
joshuaandClaude Opus 5.5 a3e3921b4f packages/auth-client: the product side of signing in through Accounts
Start a sign-in with the return path (state, nonce, PKCE), finish it,
sign-out address, back-channel logout tokens and Accounts' signed
user.* calls. Tested against the real provider. Root lint covers
Accounts' backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:45:39 +02:00
joshuaandClaude Opus 5.5 f202a5a88e Accounts 1.0.0 frontend and @crosscode/ui
Sign-in steps (password, sign-up, email code, two-step sign-in and its
setup with recovery codes, privacy notice, news question), forgot and
reset password, the account page, admin (people, deletions, church
profile, linked products, settings, notice, licence, audit) and setup.
Strict CSP with a nonce per page; church colours from the profile.
@crosscode/ui gets its first components (shell, card, fields, buttons).
Plan: roles stay in each product (asked 2026-11-18).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:42:45 +02:00
joshuaandClaude Opus 5.5 a888260f01 Accounts: product tests (sign out everywhere, back-channel calls, deletion, export, Connect, admin), lib tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:36:18 +02:00
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00
joshuaandClaude Opus 5.5 45c6539bf1 Contracts 1.5.0: OIDC client paths, client secret from the link, church.changed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:15:27 +02:00
joshuaandClaude Opus 5.5 6c284099ef docs: Accounts plan decisions confirmed, library versions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:14:28 +02:00
joshuaandClaude Opus 5.5 6bdabeb871 docs: plan for Accounts 1.0.0 (phase 3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:10:54 +02:00
joshua 78dd903b2d Merge branch 'feat/events-2.4' 2026-11-18 13:02:21 +02:00
joshuaandClaude Opus 5.5 716d47242a Events 2.4.0 frontend, deploy and docs: Linked products, linked events, seo
- Site settings → Linked products (Connect, Show events from, Publish my
  events), help, command palette.
- Events from linked products on /events, the home and campus pages, and
  /events/linked/<product>/<id> (markdown with HTML off, canonical to the
  origin, no JSON-LD, not in the sitemap).
- Event page JSON-LD from @crosscode/seo; lib/eventSchema.ts removed.
- Readiness check for linked products' sync; e2e spec with a fake
  Church Website (not run yet: needs the e2e Postgres).
- crosscode: install and build the shared packages Events uses first
  (an older tag still builds as before); scripts/tests/events.bats.
- Release notes, changelogs, handovers, hub-protocol.md, and the plan's
  "Changes while building".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:58:50 +02:00
joshuaandClaude Opus 5.5 8a930d07c6 Events 2.4.0 backend: protocol v2, Linked products, the event feed
- Hub client: register and heartbeat on protocol v2 with the site's
  Ed25519 key (sent on the heartbeat until the Hub has it); falls back to
  v1 for a day if the Hub refuses v2, so the licence always refreshes.
- crosscode.link/1 Connect / Disconnect, both directions, trusted through
  the Hub's cached linkedProducts (ProductLink, LinkNonce).
- GET /api/feed/v1/events from FeedEntry (go-live, closing and selling
  out are changes; deactivated events go in deleted), event.changed to
  connected products, and showing their events (ImportedEvent).
- /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains
  crosscodeEvent and priceRangeCents for the JSON-LD.
- Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:24:29 +02:00
joshuaandClaude Opus 5.5 390b80e56e packages/seo: schema.org JSON-LD and meta helpers on @crosscode/contracts
eventJsonLd (crosscode.event/1), churchJsonLd (crosscode.church/1),
canonicalUrl, pageMeta and jsonLdString (ROADMAP-v3 §11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:01:20 +02:00
joshuaandClaude Opus 5.5 4952e2cb0f Contracts 1.4.0: crosscode.link/1 and a public key in the v2 heartbeat
- crosscode.link/1 (link.connect / link.connected / link.disconnect), with
  signLink / verifyLink, PEM conversion, link secrets and nonces.
- The v2 heartbeat can carry the install's publicKey; the reply says
  saved / matches / mismatch (Hub 2.2.0). Never a failed heartbeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:58:26 +02:00
joshua 9d585c94aa Merge branch 'docs/events-2.4-plan' 2026-11-18 11:54:36 +02:00
joshuaandClaude Opus 5.5 0cc72aaaad docs: plan for Events 2.4.0, handovers after 2.3.1 / agent 1.0.1 / Hub 2.1.1
EVENTS-2.4-PLAN.md: protocol v2 (public key in the v2 heartbeat, Hub 2.2.0),
Linked products and Connect (crosscode.link/1, contracts 1.4.0), the event
feed, showing sibling events, and packages/seo. Six decisions to confirm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:54:36 +02:00
joshuaandClaude Opus 5.5 6db2f439b4 Release events@2.3.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:20:01 +02:00
joshua 28603f2301 Merge branch 'fix/next-16.4.6' 2026-11-18 10:20:00 +02:00
joshuaandClaude Opus 5.5 ee799dec98 Events: Next.js 16.4.6 (security advisories for 16.2.0-16.4.4)
Two advisories about cached data leaking across root params in `use cache` /
`unstable_cache`. Events uses neither, so it wasn't exposed, but `next build` refuses the
affected versions. The root overrides pinned next and eslint-config-next to 16.4.3; both now
16.4.6. Also brings apps/events/package.json up to the release (left at 2.2.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:20:00 +02:00
joshuaandClaude Opus 5.5 0312767d75 Release agent@1.0.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:01:23 +02:00
joshua 46e8c15602 Merge branch 'fix/central-status' 2026-11-18 10:01:23 +02:00
joshuaandClaude Opus 5.5 f1d6234800 Agent: answer status on the central server itself
Central servers only get the agent (install.sh --central), not the crosscode script, but a
central agent accepts status jobs and ran `crosscode status` for them, which failed with
`spawn /usr/local/bin/crosscode ENOENT`. A central agent now reports its own stats (frps and
the agent version) for status; church servers still run crosscode status.

Also ignores temp/ (local screenshots).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:01:22 +02:00
joshuaandClaude Opus 5.5 a286f8abce docs: handover after the 2.3.0 / agent 1.0 / Hub 2.1 release
Root HANDOVER: phases 1b–1d released and VM tested, the nine bugs the VM
test found, rollout next. Events HANDOVER: 2.3.0, where two-factor and the
Hub-install pieces live. AGENT-1.0-PLAN and EVENTS-2.2-PLAN: tested and
released, the VM changes; ROADMAP §9 marked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdni7EfytGYqQTprME
2026-11-17 22:41:10 +02:00
joshuaandClaude Opus 5.5 d985a4c853 docs: rollout checklist for Hub 2.1, the agent and Events 2.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdni7EfytGYqQTprME
2026-11-17 22:29:06 +02:00
joshuaandClaude Opus 5.5 eb4e44a735 Release events@2.3.0, contracts@1.3.0 and agent@1.0.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdni7EfytGYqQTprME
2026-11-17 22:23:11 +02:00
joshua 3bcde954fb Merge branch 'feat/totp' 2026-11-17 22:23:11 +02:00
joshua 328b2ce11a Merge branch 'feat/agent-1.0' 2026-11-17 22:15:31 +02:00
joshuaandClaude Opus 5.5 f4955bee9d Fetch tags with --force: the release tag on the server wins
Found in the VM test: when a tag had moved (a re-tagged release), a church's
fetch refused it and every later deploy failed its checks. The deploy checks
out the tag the Hub asked for, so the remote's tag is the one to trust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdni7EfytGYqQTprME
2026-11-17 19:08:53 +02:00
joshuaandClaude Opus 5.5 570f2dda5a PM2 runs under its own systemd unit, never as a child of the agent
Found in the VM test: a site's PM2 daemon started from the agent's install
job belonged to the agent's service, so stopping or updating the agent took
down every site it had installed. Before any PM2 command as a site user,
the scripts now make sure that user's daemon runs under pm2-<user> (moving
one that runs elsewhere, keeping its process list). The agent's stats no
longer start an empty daemon by asking one that isn't running. Uninstall
stops the unit before removing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:40:12 +02:00
joshuaandClaude Opus 5.5 19709c2c75 frpc: restart it the first time the admin lines are added (a reload can't work yet)
Found in the VM test: the new install's tunnels never opened, because
frpc only reads admin_addr when it starts, so the first reload failed.
That first time (and whenever a reload fails), frpc is restarted under
systemd and the report says so; later changes reload as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:48:28 +02:00
joshuaandClaude Opus 5.5 f3f6dc8f7a Events env template: HUB_PUBLIC_KEY in the defaults, for a Hub other than production
Without it a site installed from a staging Hub (or the VM test's Hub)
can't check its licence. Blank in production, so it isn't written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:35:50 +02:00
joshuaandClaude Opus 5.5 0d7e6b52d2 agent install / self-update: install the root's build tools too
Found in the VM test: npm ci -w packages/contracts -w apps/agent skipped
the monorepo root's devDependencies (tsup, typescript), so the agent
couldn't be built. --include-workspace-root brings them in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:35:13 +02:00
joshuaandClaude Opus 5.5 2479cbbd0a deploy: after a failed migration, mark it rolled back so later deploys aren't blocked
Found in the VM test: Prisma records a failed migration and then refuses
every later migrate deploy (P3009), so one broken release left a church
unable to update. On rollback, failed migrations the previous release
doesn't have are marked rolled back (prisma migrate resolve); the
backup still has the database as it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:30:18 +02:00
joshuaandClaude Opus 5.5 c8d46ef2d9 adopt: apply the release's new migrations in the switch-over (events@2.2.0 has one)
Found in the VM test: adopt refused events@2.2.0 because the AI tokens
migration made it into the release, and adopt only moved installs with
no migrations. Now the migrations the release has and the old install
doesn't run after the backup, while neither version runs; a failure
starts the old install again. They're recorded (EVENTS_ADOPT_MIGRATIONS)
so adopt --undo can still go back past them (they only add columns).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:15:09 +02:00
joshuaandClaude Opus 5.5 ee65ff358c Events 2.3.0 (phase 1c): two-factor with an authenticator app, recovery codes
- TOTP (RFC 6238) next to email and WhatsApp: QR code and key to set up,
  the app's first code confirms it, a code can't be used twice, nothing
  is sent. The secret is stored encrypted.
- 10 single-use recovery codes whenever two-factor is turned on, shown
  once; accepted at sign-in in place of any code; a new set on request.
- Admins see each account's method; Reset 2FA clears the app and codes.
- Profile & Security, sign-in and Users pages; API types; 10 new tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:55:22 +02:00
joshuaandClaude Opus 5.5 b207d17db8 WIP Events 2.3.0: TOTP util, schema and migration for authenticator-app 2FA
Not wired up yet: twoFactor.js, login, enable/confirm/disable, recovery
codes endpoints and the frontend still to do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:37:52 +02:00
joshuaandClaude Opus 5.5 92869d2683 crosscode: envtpl as .cjs (Node CommonJS for the root lint)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:26:00 +02:00
joshuaandClaude Opus 5.5 d61b3e5978 Docs: agent 1.0 built (changes while building), handover, changelogs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:19:41 +02:00
joshuaandClaude Opus 5.5 1eeaf4d94f Agent 1.0.0: polls the Hub for signed jobs, runs crosscode, sends reports and stats
apps/agent (docs/AGENT-1.0-PLAN.md §3-4, §10): listens on nothing; checks
every job (pinned Hub key, server, time window, replays for 90 days,
type per mode, strict arguments) before running crosscode with an
argument array; opens the sealed config into a root-only file only for
the job; redacts log lines; keeps unsent reports in an outbox; encrypts
exports before upload; check-ports on the central server (read-only);
self-update with automatic revert. One bundled dist/cli.js, a systemd
unit and the install script that joins a server with a one-time token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:58:08 +02:00
joshuaandClaude Opus 5.5 e9e9b5a97f crosscode: --json reports, --config, env templates, frpc tunnels, restart/export/uninstall/purge
- Every command takes --json (crosscode.script-report/1 on stdout, the
  log on stderr) and --config (the .env values by layer, from the agent).
- .env files come from the release's env.template.json (lib/envtpl.js):
  written whole on install; on deploy only new variables are appended,
  and a new required one with no value stops the deploy at the checks.
- install --frp: Hub-given ports, a marked frpc.ini block (backup,
  frpc verify, reload; [common] admin lines added once), no nginx.
  A database on another server via DB_ADMIN_URL. Refuses an existing
  database or role. Everything the run made is removed if it fails.
- restart, export (crosscode.church-export/1 ZIP), uninstall (final
  backup, uploads and .env kept 30 days) and purge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:50:19 +02:00
joshuaandClaude Opus 5.5 350ab9f4e8 Events: env template, church export, register with HUB_LICENCE_KEY
- apps/events/env.template.json (crosscode.env-template/1): every .env
  variable with its layer (server, defaults, install, generated).
- scripts/export-church.ts writes crosscode.church-export/1 (export-only
  references, no internal ids or secrets) for crosscode export.
- Installs made from the Hub register by themselves on first start when
  HUB_LICENCE_KEY is set (retries while the Hub is unreachable).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:06:01 +02:00
joshuaandClaude Opus 5.5 90a98a4306 contracts 1.3.0: agent jobs, reports, stats, join/poll, env templates, church export
Jobs of fixed types with strict argument schemas, signed by the Hub with
Ed25519 over canonical JSON. Agent requests signed with the server's
Ed25519 key. Config sealed to the server's X25519 key (X25519 + HKDF +
AES-256-GCM; Node has no XSalsa20). Exports encrypted with a key that
only travels in the download link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:02:24 +02:00
joshuaandClaude Opus 5.5 53e15fdd69 Release events@2.2.0 and contracts@1.2.0
Events 2.2.0: the move into the monorepo and the crosscode script, plus
AI use in tokens and the backend under /api. Contracts 1.2.0: token
fields on the AI status. Agent phase 1d moves to contracts 1.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:38:09 +02:00
joshua a0ab22fbf3 Merge branch 'feat/api-prefix'
# Conflicts:
#	apps/events/CHANGELOG.md
2026-11-17 11:31:34 +02:00
joshua 52099c310d Merge branch 'feat/ai-tokens' 2026-11-17 11:31:06 +02:00
joshuaandClaude Opus 5.5 61a64cf339 Docs: AI tokens and /api under Events 2.3.0 in the roadmap and handover
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:12:01 +02:00
joshuaandClaude Opus 5.5 afaccf79d1 Events: everything the backend serves is under /api (for 2.3.0)
The site and its API can share one address with one proxy rule (/api to
the backend, everything else to the frontend). Status page at /api (/
redirects), /api/health, /api/docs/v2, /api/uploads. Stored upload
paths stay /uploads/… and are given out as /api/uploads/…. Old paths
still answer (/health, /uploads) or redirect (/docs, /docs/v2), so
two-address sites keep working. DEPLOYMENT.md and the agent plan
describe the single rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:11:46 +02:00
joshuaandClaude Opus 5.5 38ebce24ab Events: AI use in tokens, not rand (for 2.3.0); contracts: token fields on the AI status
Site settings → AI, the usage tables and the 80% email show input/output
tokens and the percentage; the rand amounts from the Hub are dropped on
arrival. AiCall stores each call's tokens (migration ai_tokens). v2
/ai/status and /ai/usage carry tokens instead of cents. Needs Hub 2.0.1
for the token figures; older Hubs show the percentage only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:59:36 +02:00
joshua e8853cf0c8 Merge branch 'feat/crosscode-script' 2026-11-12 19:27:57 +02:00
joshuaandClaude Opus 5.5 c442fe0d42 crosscode script: deploy, status, install, adopt (Events 2.2.0, plan §4-5)
One script for installing, updating and moving church installs, replacing
hope-events' scripts/deploy.sh and install.sh:

- deploy <church> [events] / --every-church, with --version, --main, --check
  and --allow-local-changes: checks every product first (files changed by
  hand, Node, release requirements from WHATS-NEW.md headings), then each
  product in order with backup, checkout, install, migrate, build, PM2 reload
  and a /health version check; a failure rolls that product back and stops.
- status [<church>]: checked-out and latest release, /health, and the old
  folder kept after adopt.
- install <church> --products events --domain <address>: a new church under
  /var/www/sites/<church>, writing church.env.
- adopt <church> --events-dir <old> builds the monorepo checkout next to the
  running install and switches PM2 over; adopt --undo goes back to it.

Product hooks live in scripts/products/events.sh. shellcheck (lint:scripts)
and 47 bats tests (test:scripts) are part of npm run check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:17:06 +02:00
joshua f174285711 Merge branch 'move/events' (Cross Events into apps/events) 2026-11-12 17:34:45 +02:00
joshuaandClaude Opus 5.5 47f346b0a6 Events move: workspaces and one root lockfile, versions pinned to 2.1.1
- Workspaces: apps/events/backend and apps/events/frontend; apps/events itself
  excluded (npm doesn't install node_modules for a workspace nested in another).
  Its dev tools (Playwright, axe, concurrently) move to the root.
- Packages renamed @crosscode/events, -backend, -frontend; nested lockfiles removed.
- allowScripts moved to the root (npm ignores it in workspaces), same choices.
- Direct dependencies that moved pinned to their 2.1.1 versions in root overrides;
  @sentry/node pinned only inside the backend.
- Same results as 2.1.1: 52 suites / 711 backend tests, typecheck, both builds.
- EVENTS-2.2-PLAN §2 and HANDOVER updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:34:45 +02:00
joshuaandClaude Opus 5.5 1ef1af64b7 Events move: root lint ignores apps/events, drop doc pointer stubs, fix handover links
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:38:35 +02:00
joshuaandClaude Opus 5.5 243021c81e Cross Events moves into the monorepo (apps/events), from hope-events e6c9670
History rewritten under apps/events/ (git filter-branch). Commit hashes changed;
the originals stay in the archived hope-events repo. Old v… tags are not brought over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:37:48 +02:00
joshua a800d448f4 Merge branch 'docs/server-agent' 2026-11-12 16:26:51 +02:00
joshuaandClaude Opus 5.5 c398e8071d Docs: server agent and Hub 2.1.0 plan (phase 1d, decisions 27-37)
Agent on every server runs installs, scheduled/emergency updates and
uninstalls on signed jobs from the Hub, polls only (no listening port),
appends to frpc.ini in marked blocks, builds .env files from per-server
config in the Hub. FastPanel and DNS stay manual (emailed instructions).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:26:51 +02:00
joshua 934f7a9eed Merge branch 'docs/adopt-decisions' 2026-11-05 13:51:09 +02:00
joshuaandClaude Opus 5.5 4e58c5c07e Docs: adopt builds next to the install and switches over; adopt --undo (decisions 25-26)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:51:08 +02:00
joshua 0ab0ca9fa0 Merge branch 'docs/moved-to-platform' 2026-11-05 09:48:33 +02:00
joshuaandClaude Opus 5.5 897b27cc42 Docs: roadmap v3 and Hub protocol moved to crosscode-platform/docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:31 +02:00
joshua 8032a5d9e2 Merge branch 'docs/roadmap-and-events-move' 2026-11-05 09:48:28 +02:00
joshuaandClaude Opus 5.5 633d65eec9 Docs: roadmap and Hub protocol move here; handover and Events 2.2.0 plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:27 +02:00
joshuaandClaude Opus 5.5 2bb5580e10 Merge branch 'docs/hub-2-released'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:10:34 +02:00
joshuaandClaude Opus 5.5 015495ab56 Docs: Hub 2.0.0 released (phase 1); hub-protocol.md with protocol v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:10:33 +02:00
joshuaandClaude Opus 5.5 d62a652be2 Merge branch 'feat/contracts-release-requires' (contracts@1.1.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:45:40 +02:00
joshuaandClaude Opus 5.5 11e28502ea Contracts 1.1.0: optional requires on Hub releases
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:45:40 +02:00
joshuaandClaude Opus 5.5 9dc2fa8af4 Merge branch 'docs/sites-folder'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:54:05 +02:00
joshuaandClaude Opus 5.5 4cbfcddfbd Docs: church installs under /var/www/sites/<church>/<product>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:54:05 +02:00
joshuaandClaude Opus 5.5 fbf9d3553d Merge branch 'docs/roadmap-monorepo-deploy'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:48:36 +02:00
joshuaandClaude Opus 5.5 e78534328e Docs: monorepo move, crosscode deploy script, releases per product
ROADMAP-v3 decisions 21-24: Cross Events moves into crosscode-platform
(2.2.0); one crosscode script deploys Accounts plus the products named;
the Hub tracks releases per product with requirements; the Hub gets the
contracts as a committed file, not from the package registry. Cross Events
versions in the build order move up by one. HANDOVER updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:48:36 +02:00
joshuaandClaude Opus 5.5 6bb80f75d1 Roadmap v3: four Website templates; SEO for every public site
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:04:13 +02:00
joshuaandClaude Opus 5.5 5ab755cc63 Roadmap v3: Hub protocol v2 (today's is v1), event-feed schema, enum rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:47:42 +02:00
joshuaandClaude Opus 5.5 6a5aa29494 Roadmap v3: sign-in returns to where you came from; crosscode-site per phase
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:31:29 +02:00
joshuaandClaude Opus 5.5 ca7a14bcf8 Roadmap v3: decisions, pricing and authenticator-app 2FA; handover updated
One install of each product per customer; House of Prayer booking
defaults; email and WhatsApp only (no push); Accounts hidden from
members. Pricing: Website R99 with 5 GB plus storage add-on, App from
R99, address once per church (own domain, crosscode.co.za address R10,
domain included R25). Authenticator app 2FA as Cross Events 2.2.0.
Handover now points at ROADMAP-v3; nothing left open in ROADMAP-v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:48:23 +02:00
joshuaandClaude Opus 5.5 545880fdc7 Roadmap v3: Accounts, Church Website, Church App, Cross Code Hub
Plan for selling three products from one Hub: shared users through a
per-church Accounts service, event sync in any direction on one shared
format (crosscode.event/1), PM2 installs per product per church.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:14:24 +02:00
joshua 01f9a3eeac Merge branch 'fix/feedback-background-send' 2026-11-03 14:11:44 +02:00
joshuaandClaude Opus 5.5 53797e4447 Feedback Send now and Remind run in the background (2.1.1)
- Send now and Remind answer straight away with who they're going to and
  queue the feedback-send task; the Feedback page refreshes to show progress.
- One-off background tasks (enqueueTask in src/jobs/index.js): pg-boss with
  retries, or in-process after the response when the queue is off.
- Reminders are claimed with the 24-hour rule, so two tasks at once never
  remind the same person twice.
- Tests: tests/tasks.test.js, tests/feedbackPage.test.ts, e2e/feedback.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:11:44 +02:00
joshuaandClaude Opus 5.5 a345b3c824 Handover: Hub 1.7.0 bills on the income bands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:42:46 +02:00
joshua aca6f7728d Merge branch 'feat/feedback-page' 2026-11-03 13:03:05 +02:00
joshuaandClaude Opus 5.5 9dda0d1851 Feedback page: results, responses, who hasn't answered, reminders (2.1.0)
- Supervisor -> Feedback (supervisors and admins, campus-scoped): every
  event's form with answered of asked, response rate, average rating and
  last reminder; per event the results per question (with the AI summary),
  each response, and on named forms who was asked and who has answered.
- Remind those who haven't answered (or one person on a named form): a
  fresh link, plus the form to anyone eligible who hasn't had it; nobody gets
  the form or a reminder twice within 24 hours. The 3-day job is unchanged.
- Anonymous forms show no names and no list of who has answered.
- FeedbackInvite.reminderCount (migration 20261103120000_feedback_reminders);
  access log action feedback_responses; help page; dashboard and Ctrl+K links.
- Roadmap: the AI helpers on the privacy pages are dropped; 2.1.0 is the
  feedback page.
- Tests: tests/feedbackPage.test.ts, e2e/feedback.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:03:05 +02:00
joshua c018772ded Merge branch 'feat/billing-income-bands' 2026-11-03 12:18:01 +02:00
joshuaandClaude Opus 5.5 aabf3cbe07 Billing income bands up to R10m, 12-month event income in the heartbeat (2.0.2)
- Heartbeat income bands widened from "over R100 000" to 14 bands up to
  "over R10 000 000"; every licence-tier edge is a band edge (tested).
- New income.eventIncome12m: last 12 months' event income without donations,
  sponsorships or donation legs, which the licence tier is billed on.
- Fix: donation legs were counted twice in the heartbeat income bands.
- Protocol doc, roadmap pricing decisions, changelog, what's new, handover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:18:01 +02:00
joshua cebfe52be5 Merge branch 'fix/ai-summary-all-reports' 2026-11-02 18:42:27 +02:00
joshuaandClaude Opus 5.5 40fa8b2dba Summarise this report on every report (2.0.1)
The eight reports that list people get the AI summary too, sent as
anonymised totals built on the screen (aiReportData.ts): no names,
contact details, notes or comments; consent and medical only as counts.
The server refuses personal columns on those reports and logs each
summary in the access log (ai_report; sensitive for consent and medical).

Roadmap §18: 2.0.1, then crosscode.co.za, then 2.1.0 (AI helpers on the
Consent log and Access log).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:42:27 +02:00
joshua 8d7269a1e2 Merge branch 'docs/marketing-site' 2026-11-02 18:01:25 +02:00
joshuaandClaude Opus 5.5 d33284b1ec Docs: marketing site decisions (crosscode.co.za)
crosscode.co.za as Cross Code's main site with a Cross Events page;
church website and app as "coming later"; repo joshua/crosscode-site;
own server; no prices yet; contact form to info@crosscode.co.za;
privacy notice and terms of use; no cookies. Content from Joshua later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:01:23 +02:00
joshua 391baa0d67 Merge branch 'release/2.0' (2.0.0) 2026-11-02 17:49:34 +02:00
joshuaandClaude Opus 5.5 b58123adab Release 2.0.0
AI helpers, API v1 removed, Argon2id passwords, React Compiler lint
rules back to errors, migration guide. Docs (HANDOVER, roadmap) mark
2.0.0 as released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:49:30 +02:00
joshuaandClaude Opus 5.5 abd2c36e97 WIP 2.0.0: React Compiler lint rules back to errors; docs
- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

e2e 102/102 (PayFast sandbox skipped); production build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:45:25 +02:00
joshuaandClaude Opus 5.5 3f59164ab2 WIP 2.0.0: v1 removed; Argon2id passwords; node-fetch gone
- /api (v1) answers 410 API_V1_REMOVED, except provider webhooks
  (/api/webhooks/*, /api/whatsapp/webhook) and links in sent messages
  (308s, one-click POST). 43 v1 route files and deprecation.ts removed;
  /docs redirects to /docs/v2; API_DOCUMENTATION.md points there.
- Read-only and impersonation lists name v2 paths only. The campus
  scope route test now runs over v2 routes (v2CampusScope.test.ts).
- Passwords hashed with Argon2id (@node-rs/argon2); bcrypt hashes still
  sign in and are re-hashed at the next sign-in.
- e2e on /api/v2 only (v2() helper); Playwright waits on /api/v2.
- MIGRATING-TO-2.md with the full v1 -> v2 table.
- Two documented response shapes corrected.

Backend 690 tests and e2e 102/102 (PayFast sandbox skipped) pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:35:06 +02:00
joshua 57b3c41067 Merge branch 'main' into release/2.0 (1.52.3)
# Conflicts:
#	CHANGELOG.md
2026-11-02 15:15:08 +02:00
joshua fa48e3bb24 Merge branch 'fix/read-only-v2' 2026-11-02 15:14:50 +02:00
joshuaandClaude Opus 5.5 edd3ee6e76 Fix: licence read-only mode blocks the v2 routes too (1.52.3)
The read-only guard only listed v1 paths, and every screen has used
/api/v2 since 1.51.15, so a suspended, revoked or unlicensed site could
still create events, take registrations and start payments. The v2
successors of each blocked v1 route are blocked now; a test checks each
blocked v2 path exists in the OpenAPI document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:14:50 +02:00
joshua b41dbab667 Merge branch 'main' into release/2.0 (1.52.2)
# Conflicts:
#	CHANGELOG.md
#	docs/HANDOVER.md
2026-11-02 14:13:12 +02:00
joshua 76f17ab0e9 Merge branch 'fix/deploy-local-changes' 2026-11-02 14:04:27 +02:00
joshuaandClaude Opus 5.5 50639088b2 Deploy: stop first when files in the install were changed by hand (1.52.2)
A setup wizard run on one server added files to backend/src that the
backend build picked up, so the deploy failed part-way and rolled back.
deploy.sh now lists files git reports as changed or added (ignored files
and the PM2 config don't count) and stops before backing up or checking
out. --check runs only that; ALLOW_LOCAL_CHANGES=1 deploys anyway; the
script also runs from a copy outside the install (the folder you're in).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:03:12 +02:00
joshua d53eba29ea Merge branch 'main' into release/2.0 (1.52.0, 1.52.1)
# Conflicts:
#	CHANGELOG.md
#	docs/HANDOVER.md
2026-11-02 13:45:28 +02:00
joshua 72edb4da30 Merge branch 'docs/openapi-complete' 2026-11-02 13:27:05 +02:00
joshuaandClaude Opus 5.5 d74af96f1d Docs: every v2 route documents its body, answer and parameters (1.52.1)
Most routes answered by a v1 handler showed an empty body and
`data: unknown` in /docs/v2. Each now documents what its handler reads
and answers, and every path and query parameter is described.

- `documented: { body?, response? }` on v1Route/defineRoute, with shared
  shapes in src/v2/docs.ts. Documentation only: not enforced, so nothing
  that works can start failing; outside production a body or answer that
  doesn't fit is logged ("doesn't match its documented schema").
- QUERY_HELP / PATH_HELP describe common parameters; empty bodies say
  "No body needed".
- Declared the funnel's eventIds and webhook deliveries' status/before.
- tests/v2Docs.test.ts keeps the document complete; frontend types
  regenerated, three call sites' types tightened (no payload change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:26:15 +02:00
joshua 6e64e64bff Merge branch 'fix/door-tickets-corrections' 2026-11-02 12:24:00 +02:00
joshuaandClaude Opus 5.5 db214a1013 Fix: door and manual registrations get their tickets; admin Corrections (1.52.0)
On events with a required attendee form, tickets waited for the forms, but
At the door and Manual registration never asked for them: payment was
recorded and nobody could be checked in.

- The form pops up at the door and in Manual registration; "Fill in later"
  (any staff) issues the tickets once paid and sends the payer a link
  (Registration.formWaivedAt, POST /api/v2/registrations/{id}/form-later).
- One form per person on picked-session bookings; a required form with no
  questions no longer holds tickets back; every caller asks the ticket
  generator (formsOutstanding).
- Kiosk asks for the forms the server says are missing; headings show as text.
- Admin Corrections page and /api/v2/corrections: issue missing tickets,
  pay later (ticketsReleasedAt), make it free (complimentaryDiscount),
  check in or undo after the event.
- Migration 20261102120000_corrections; unit and e2e tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:01:10 +02:00
joshuaandClaude Opus 5.5 ba121118ea WIP 2.0.0: message drafts use event placeholders only with an event
Found by the first real eval run (Sonnet 5.5 through the local Hub,
19/19 checks): without an event the drafts still used {{event.title}}
and added an event-details block. The instructions now offer those
placeholders only when an event is given; the eval checks for it, and
adds up split themes when counting feedback. Route tests for the five
AI helpers in v2.test.ts; the eval script loads backend/.env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMeckMWrKPfc1MMyMJF
2026-10-30 18:25:57 +02:00
joshuaandClaude Opus 5.5 4924d1ed76 WIP 2.0.0: AI buttons on the five screens, eval set, privacy notice
Describe your event (new event), Improve/Shorter/Fix mistakes (event
description, banner, email and WhatsApp boxes), Draft with AI (email and
WhatsApp attendees), Summarise this report (people-free reports) and
Summarise feedback (per event). Built-in privacy notice text for AI
(2.0.0 entry in BUILT_IN_UPDATES). npm run ai:eval runs the trial cases
through the Hub with fact checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMeckMWrKPfc1MMyMJF
2026-10-30 18:19:46 +02:00
joshuaandClaude Opus 5.5 d4f54f2cc8 WIP 2.0.0: the five AI helpers' API
src/ai/helpers.ts: instructions, schemas and inputs for draft event,
summarise report (people-free reports only), draft message, summarise
feedback (no names, access-logged) and improve text. Contact details
are swapped for placeholders before sending and restored after; every
helper gets today's date; weekday clashes and break-even over capacity
are checked in code. v2 routes /ai/draft-event and friends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:38:16 +02:00
joshuaandClaude Opus 5.5 cbdc7ad10a Docs: Sonnet 5.5 for every AI helper (Hub 1.6.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:25:16 +02:00
joshuaandClaude Opus 5.5 20d53b79f1 Docs: 2.0 progress, marketing site plan, AI tested
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:58:48 +02:00
joshuaandClaude Opus 5.5 dbec47aae3 WIP 2.0.0: AI helper plumbing (status, usage, Site settings -> AI)
The site calls AI through the Hub (protocol 3b, Hub 1.6.0): src/ai
works out whether the AI buttons show (licence token first, then the
Hub, cached a minute), runs a helper call with per-helper switches and
a per-person daily limit, logs AiCall rows, and emails admins at 80%.
v2 /ai/status, /ai/usage, /ai/settings; useAiStatus, AiButton, AiTab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:25:36 +02:00
joshua 838a6b3c3d Merge branch 'docs/handover-roadmap-tidy' 2026-10-30 09:00:49 +02:00
joshuaandClaude Opus 5.5 0f915d345d Docs: bring HANDOVER and ROADMAP-v2 up to date after 1.51.17
HANDOVER: version table in order with 1.51.4/1.51.5 added; Next up
renumbered with the 2.0 clean-ups (lint rules, node-fetch, password
hashing); event picker points at fetchManagedEvents; stale lines fixed.
ROADMAP: status rewritten as a dated summary; section 14 marks what's
done and that CI was removed; Haiku prices flagged to check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:00:49 +02:00
joshua 792b5b291b Merge branch 'fix/forgot-password-enumeration' 2026-10-30 08:51:41 +02:00
joshuaandClaude Opus 5.5 839a56ddbd Security: forgot password and sign-in don't reveal accounts (1.51.17)
- Forgot password answers the same (message, status, timing) for every email; the reset link
  is made and sent after the answer. Rate-limited like sign-in.
- Sign-in with an unknown email is refused exactly like a wrong password, after a password
  check against a stand-in hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:51:41 +02:00
joshuaandClaude Opus 5.5 0e4a251c9a WIP 1.51.17: forgot password and sign-in don't reveal accounts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:47:04 +02:00
joshua 558c433b8f Merge branch 'feat/api-v2-webhooks-links' 2026-10-30 08:34:41 +02:00
joshuaandClaude Opus 5.5 82e8f9cd62 Incoming webhooks and message links on API v2 (1.51.16)
- /api/v2/webhooks/{yoco,payfast,whatsapp}; new provider set-ups use them, the v1 addresses
  keep working with the same handlers.
- Calendar and one-click unsubscribe links point at v2; old links answer 308 (a one-click POST
  to the old address is still handled there).
- /api/webhooks/whatsapp runs the real WhatsApp handler (was an empty stub).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:34:41 +02:00
joshuaandClaude Opus 5.5 d31ffdce0c WIP 1.51.16: incoming webhooks and message links on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:30:05 +02:00
joshua 20d43b63c2 Merge branch 'feat/api-v2-privacy-admin' 2026-10-30 08:23:49 +02:00
joshuaandClaude Opus 5.5 044a113af5 Privacy and admin on API v2 (1.51.15)
- v2: my privacy, unsubscribe links, the privacy admin, audit log, jobs, impersonation,
  settings and first-run set-up, the Hub, outbound webhooks, backups, Yoco/PayFast settings.
- Every call the app makes is now on /api/v2 (incoming webhooks and message links: 1.51.16).
- v1Route handles res.download/sendFile; impersonation end/log allowed on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:23:49 +02:00
joshuaandClaude Opus 5.5 68c6559136 WIP 1.51.15: privacy and admin on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:19:24 +02:00
joshua 7b20ffbe08 Merge branch 'feat/api-v2-people-messaging' 2026-10-30 08:11:48 +02:00
joshuaandClaude Opus 5.5 23ff8dd31f People and messaging on API v2 (1.51.14)
- v2: the rest of accounts (code resend, password reset, activation, sessions, closing,
  activity, two-step sign-in; admin users), /event-listing, messaging and broadcasts,
  scheduled messages, automations, WhatsApp connection, banner, saved filters, dashboards,
  stats, analytics, report files.
- GET /me carries the session fields the app needs (prompts, campus scope, 2FA required).
- defineRoute refuses duplicate routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:11:48 +02:00
joshuaandClaude Opus 5.5 3b5ba6b9c6 WIP 1.51.14: GET /me carries the session fields the app needs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:07:06 +02:00
joshuaandClaude Opus 5.5 ba351be029 WIP 1.51.14: people and messaging on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 17:02:26 +02:00
joshua 1bc236ddd1 Merge branch 'feat/api-v2-kids-volunteers' 2026-10-29 16:50:11 +02:00
joshuaandClaude Opus 5.5 165e4d14f0 Kids check-in and volunteers on API v2 (1.51.13)
- v2: my family, kids set-up and the check-in desk (board, families, check-in/out, codes,
  offline), volunteering (roles, sign-up, swaps, self check-in) and rosters (roles, assigning,
  manual check-in, hours).
- Frontend: kids desk, rooms, family, serving and rosters on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 16:50:10 +02:00
joshuaandClaude Opus 5.5 d1452c6645 WIP 1.51.13: kids check-in and volunteers on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 16:46:40 +02:00
joshua 11a90e572e Merge branch 'feat/api-v2-tickets-attendance' 2026-10-29 16:40:28 +02:00
joshuaandClaude Opus 5.5 237cd89f6a Tickets and attendance on API v2 (1.51.12)
- v2: tickets (mine, one, send, issue, transfers, scans), scan locks, the attendance register
  and its export, certificates, allocations.
- Frontend: apiV2Raw() for string-path helpers; every ticket/attendance screen on v2.
- v1Route can run a v1 router by URL; an unanswered chain is a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 16:40:27 +02:00
joshuaandClaude Opus 5.5 fe6034f10f WIP 1.51.12: tickets, scan locks, attendance, allocations on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:52:31 +02:00
joshua 91fa42ba5f Merge branch 'feat/api-v2-money' 2026-10-29 13:47:49 +02:00
joshuaandClaude Opus 5.5 50205c03f0 Money on API v2 (1.51.11)
- v2: payments, refunds, donations, payment links and the pay page, providers, cash-ups,
  provider transactions, waitlist, sponsorship, consent, form responses, feedback.
- src/v2/viaV1.ts: v1Route() answers a v2 route with the v1 handler in-process.
- /docs/v2 opens collapsed with a filter (Swagger UI stopped drawing past ~130 endpoints).
- Frontend: every money screen on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:47:49 +02:00
joshuaandClaude Opus 5.5 fb36e9c8ac WIP 1.51.11: money on v2 via v1 handlers (viaV1 adapter)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:43:36 +02:00
joshua de08f057ad Merge branch 'feat/api-v2-registrations-staff' 2026-10-29 13:16:59 +02:00
joshuaandClaude Opus 5.5 a7a9382a93 Managing registrations on API v2 (1.51.10)
- v2: staff list (paged), event registrations, registration in full (+ /me), status, manual
  registration, bulk, items, invoice, coupon, attendees and form links, form drafts and responses.
- src/services/registrationAdmin.ts holds the rest of registrationController.js (now v1 wrappers).
- Frontend: fetchAllRegistrations(); every registration screen on v2.
- Roadmap: money gets its own release (1.51.11); webhooks and links move to 1.51.16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:16:59 +02:00
joshuaandClaude Opus 5.5 7eb6f99e97 WIP 1.51.10: registration management on v2 (routes, frontend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:04:31 +02:00
joshuaandClaude Opus 5.5 5a3bfa1100 WIP 1.51.10: registration management moved to src/services/registrationAdmin.ts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:57:02 +02:00
joshua 4fa0d831d8 Merge branch 'feat/api-v2-series-deals' 2026-10-29 12:39:28 +02:00
joshuaandClaude Opus 5.5 af43b72c04 Series, season passes, deals and campuses on API v2 (1.51.9)
- v2: series (+ page, compare, follow), season passes (+ buy, pay, mine), bundle deals
  (+ quote), coupon codes (+ check, redemptions), campuses (+ admin, enabled, order, audience).
- src/services/series.ts, deals.ts, campuses.ts; the five controllers are thin v1 wrappers.
- v2 errors carry a service's own code as `reason`.
- Frontend: apiV2Data() for screens with their own record types; these screens on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:39:27 +02:00
joshuaandClaude Opus 5.5 684560119f WIP 1.51.9: frontend on v2 for series, passes, bundles, coupons, campuses
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:34:49 +02:00
joshuaandClaude Opus 5.5 0498ee1854 WIP 1.51.9: series, season passes, bundles, coupons and campuses on v2 (backend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:28:00 +02:00
joshua a387570098 Merge branch 'feat/api-v2-events-rest' 2026-10-29 12:18:29 +02:00
joshuaandClaude Opus 5.5 c1fc8628d3 The rest of event set-up on API v2 (1.51.8)
- v2: event in full, calendar file, alias, ticket options and variants, attachments
  (multipart), sections, planned costs, image uploads.
- src/services/eventDetails.ts and src/services/setup.ts; v1 uses them.
- v2 routes can send files (fileResponse) and take uploads (documented as multipart).
- Frontend: fetchEvent() everywhere, lib/eventSetup.ts for set-up calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:18:29 +02:00
joshuaandClaude Opus 5.5 d1927cd334 WIP 1.51.8: frontend on v2 for event detail, options, sections, attachments, costs, uploads
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:14:01 +02:00
joshuaandClaude Opus 5.5 96b9b8c23f WIP 1.51.8: sections, costs and uploads on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:08:03 +02:00
joshuaandClaude Opus 5.5 006c4db02f WIP 1.51.8: event detail, options, variants, attachments, calendar and alias on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:04:06 +02:00
joshua 4a7f75a8ec Merge branch 'feat/api-v2-events' 2026-10-29 11:57:08 +02:00
joshuaandClaude Opus 5.5 a564436f3b Setting events up on API v2, pg-boss 11 (1.51.7)
- v2: /events/manage, create, PATCH, deactivate, copy-from, notify-recipients.
- src/services/events.ts (from eventController.js, with the schedule helpers); v1 uses it.
- fetchManagedEvents() for every picker; the event wizard writes through v2.
- pg-boss 11 in its own schema (pgboss_v11); old pgboss schema left in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 11:57:08 +02:00
joshua 3e2895a9ce Merge branch 'feat/palette-excelts' 2026-10-29 11:16:38 +02:00
joshuaandClaude Opus 5.5 d74c37f5b3 Complete command palette, ExcelTS 10, roadmap: v2 for webhooks and sent links (1.51.6)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 11:14:19 +02:00
joshua fa9da3dc06 Merge branch 'chore/next16' 2026-10-29 11:00:31 +02:00
joshuaandClaude Opus 5.5 0044eec881 Next.js 16, React 19.3, ESLint 10 (1.51.5)
- Next 16 (Turbopack dev and build), React 19.3; tsconfig jsx react-jsx; images remotePatterns.
- ESLint 10 with eslint-config-next 16 flat configs; npm run lint = eslint src. React
  Compiler-era react-hooks rules set to warn (181 existing places) until screens move to v2.
- Removed the empty pass-through middleware.ts.
- e2e: wait for the palette to be ready before Ctrl+K on the staff dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 11:00:30 +02:00
joshua 2b8f39b4e7 Merge branch 'chore/dependencies' 2026-10-29 10:19:43 +02:00
joshuaandClaude Opus 5.5 81e6aeb7c2 Security and dependency updates, Node 24 for new installs (1.51.4)
- npm audit fixes: next 15.5.28 and @sentry/nextjs 10.78 (critical), zod 4.6.7, multer 2.5.0
  (high), nodemailer 10.3.0, fast-uri, ip-address (moderate). Minimum versions raised.
- cron-parser 5 (v4 unmaintained).
- install.sh installs Node 24 LTS; deploy.sh warns on Node < 22; DEPLOYMENT.md "Upgrading Node".
- Roadmap: every endpoint moves to v2 before 2.0 (1.51.5 - 1.51.11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 10:19:43 +02:00
joshua d5580cf9f0 Merge branch 'chore/roadmap-v1-decision' 2026-10-29 09:49:54 +02:00
joshuaandClaude Opus 5.5 a630b1ccc6 Roadmap: 2.0 retires only the v1 endpoints that have a v2 replacement
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:49:54 +02:00
joshua bee209faf2 Merge branch 'feat/api-v2-express5' 2026-10-29 09:46:24 +02:00
joshuaandClaude Opus 5.5 91047bcde2 Express 5, scanner on API v2, v1 deprecation headers (1.51.3)
- Express 5 (qs query parser and req.body = {} kept as in Express 4).
- Scanner and at-the-door check-in use /api/v2/checkin; look-up gives attendee, bookedBy,
  ticketOptionId.
- Shared middleware errors on /api/v2 rewritten to { error: { code, message, reason } };
  apiFetch treats reason like v1's code.
- Deprecation + Link: rel="successor-version" on v1 endpoints that have a v2 replacement.
- Roadmap: open question on how much of v1 to retire in 2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:46:24 +02:00
joshua 1b7adcf7fe Merge branch 'feat/api-v2-checkin-accounts' 2026-10-29 09:31:01 +02:00
joshuaandClaude Opus 5.5 6816e8bc67 API v2 accounts and check-in (1.51.2)
- v2: auth/signup, auth/login (+ code step, rate limited), PATCH /me; check-in look-up and
  scan returning an outcome for every normal result. Campus rule as v1.
- Sign up/login/2FA/profile moved to src/services/auth.ts; scan preview and scan to
  src/services/checkin.ts. v1 answers unchanged (ServiceError v1Status).
- Login, 2FA step, sign up and profile/password pages use v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:31:00 +02:00
joshua 440c43e530 Merge branch 'feat/api-v2-writes' 2026-10-29 09:09:09 +02:00
joshuaandClaude Opus 5.5 310684a563 API v2 registrations and payments (1.51.1)
- v2: register, get, cancel and checkout a registration (owner/admin only).
- Registration create/cancel moved to src/services/registrations.ts and online checkout to
  src/services/payments.ts; v1 controllers call the same services (ServiceError carries status).
- Typed frontend calls: npm run api:types writes openapi.json and schema.d.ts; apiV2() helper.
  Register page, Pay now and My Events cancel use v2; apiFetch reads v2 errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:09:09 +02:00
joshua 966fa256b6 Merge branch 'feat/api-v2-foundations' 2026-10-29 08:48:54 +02:00
joshuaandClaude Opus 5.5 6b3c55902e TypeScript backend and /api/v2 foundations (1.51.0)
- tsconfig (allowJs, strict .ts), npm run build -> dist/, typecheck, dev via tsx, ts-jest.
- src/index.js is now a launcher (dist build when it matches, else tsx); server moved to app.js.
- /api/v2: defineRoute with zod -> request validation, response stripping, OpenAPI 3.1 at
  /docs/v2; one error shape and one paged-list shape. First endpoints: events, event, me,
  my registrations.
- deploy.sh/install.sh build the backend; rollback to older releases skips the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 08:48:54 +02:00
joshua 7e736d8d41 Merge branch 'chore/roadmap-ai-markup' 2026-10-29 08:29:15 +02:00
joshuaandClaude Opus 5.5 ea0f0cc7ca Roadmap: AI buttons follow the cap, markup on AI usage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 08:29:15 +02:00
joshua fbf8b6199c Merge branch 'feat/event-pickers-webhook-docs' 2026-10-29 08:23:09 +02:00
joshuaandClaude Opus 5.5 b6c16a7ec4 Searchable event picker and webhook guide (1.50.2)
- EventPicker replaces the plain event dropdowns on staff/supervisor pages and the kiosk:
  upcoming first, past behind "Show past events", search across all, keyboard support.
- Reports events list can be searched ("Select these N").
- Site settings -> Webhooks: "How webhooks work" guide with headers, signature checking
  (Node.js/PHP) and an example of every event type (EVENT_TYPES[].example, shape-tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 08:23:09 +02:00
joshua b5c1224b76 Merge branch 'feat/long-lists' 2026-10-29 06:53:54 +02:00
joshuaandClaude Opus 5.5 43bbdbc405 Pagination and search on long lists (1.50.1)
Audit log: search (person, target, IP), role filter, every action in the
filter, inclusive To date. Data requests: search and paging (was cut at
200). Webhook deliveries: status filter and Load older. Supervisor Payments
loads only what it needs (unpaid registrations, recent/today/donation
payments, a person's own for refunds) instead of everything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 06:53:54 +02:00
joshua b9a886fc52 Merge branch 'feat/accessibility' 2026-10-28 15:41:19 +02:00
joshuaandClaude Opus 5.5 9548efdb45 Accessibility pass, WCAG 2.2 AA (1.50.0)
Public pages, auth, registration, payment, My Events and the kiosk: skip
link, focus ring, labels tied to fields, named quantity buttons, announced
errors, ModalOverlay popups (focus trap, Escape, focus return), contrast
and underlined in-text links, reduced motion. Branding warns about a primary
colour too light for white text and offers a darker shade. axe-core and
keyboard checks in e2e/accessibility.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:41:19 +02:00
joshua eac21f3860 Merge branch 'chore/roadmap-no-afrikaans' 2026-10-28 15:02:22 +02:00
joshuaandClaude Opus 5.5 ed1feed59d Roadmap: languages (Afrikaans) removed from scope
The accessibility pass becomes 1.50.0 and the TypeScript backend /
OpenAPI / api v2 1.51.0. Section 10 is kept for reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:02:22 +02:00
joshua 2b78193b35 Merge branch 'feat/saved-filters' 2026-10-28 14:57:34 +02:00
joshuaandClaude Opus 5.5 0bfa86bd06 Saved filters on list pages (1.49.2)
Manage registrations, Users, Events and Reports: save the current
filters under a name, apply one with a click, star one as the default
for the page (not applied over a deep link). Per person, stored on the
server, removed when an account is anonymised. /api/saved-filters.
Migration 20261028180000_saved_filters. Completes roadmap section 9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:57:34 +02:00
joshua 0f099b71f4 Merge branch 'feat/bulk-actions' 2026-10-28 14:43:01 +02:00
joshuaandClaude Opus 5.5 7b00eb7c99 Bulk actions on registrations (1.49.1)
Manage registrations: tick registrations (or all shown) and message
them (email/WhatsApp event update), mark them paid (the balance, by
method), move them to another ticket (same tickets and QR codes,
repriced, places checked), put their people in a room or group, export
to Excel, or cancel. Each runs the same handlers as doing it one at a
time, with a result per registration. POST /api/registrations/bulk,
campus-checked per id. Migration 20261028170000_registrations_bulk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:43:00 +02:00
joshua 35e58592db Merge branch 'feat/dashboard-palette' 2026-10-28 14:17:23 +02:00
joshuaandClaude Opus 5.5 ac5581a6f9 Dashboard Today and Waiting for you; Ctrl+K command palette (1.49.0)
Staff, supervisor and admin dashboards start with what's on today
(checked in vs places, children in now, volunteers here; money in today
and this week for supervisors) and, for supervisors and admins, what's
waiting for someone (unpaid registrations, consent, waitlists, cover
requests, roster gaps; for admins cashups, reconciling, privacy
requests, failed webhooks), each linking to where it's dealt with.
Ctrl+K opens a palette of pages, settings, reports and actions for the
role, with search: events, payments by amount, people and
registrations (admins). All campus-scoped. Bulk actions and saved
filters follow as 1.49.1 and 1.49.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:17:22 +02:00
joshua ecb375ecf5 Merge branch 'feat/demo-seeds' 2026-10-28 14:02:56 +02:00
joshuaandClaude Opus 5.5 a4bdbf8412 Four demo seeds; fix set-demo wiping the admin (1.48.2)
npm run demo:small | demo:events | demo:ministry | demo:multicampus
(demo:list describes them; set-demo -- --profile=<name> in backend/).
New builders: courses with sessions, attendance and certificates, a
pick-your-days conference, kids church with families, rooms and live
check-ins, volunteer rosters, a series with followers and a season
pass, and three campuses with campus-limited staff.

set-demo had failed since 1.43.0: TRUNCATE CASCADE on Campus also
emptied User (homeCampusId), deleting the admin it keeps. Tables that
User points at are now emptied with DELETE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:02:56 +02:00
joshua 434784ecbc Merge branch 'fix/privacy-notice-draft' 2026-10-28 13:15:57 +02:00
joshuaandClaude Opus 5.5 adb6e11000 Privacy notice: built-in text up to date, review flow, acceptance (1.48.1)
The built-in notice now covers volunteer rosters, event series, season
passes, webhooks, how people agree to it, and the provider-notices
storage item. Sites with their own published version see what changed
in the editor (sections marked, use new text per section or all, add
missing sections, "Done - hide this"). Account activation asks for
agreement to the terms and notice; anyone who never accepted is asked
once after login. The cookie button shows above any cookie section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:15:57 +02:00
joshua aa79168660 Merge branch 'feat/webhooks' 2026-10-28 13:00:59 +02:00
joshuaandClaude Opus 5.5 51dc908630 Outbound webhooks (1.48.0)
Site settings -> Webhooks: admins add https endpoints and choose event
types (registration created/paid/cancelled, payment received/refunded,
ticket checked in, account created, event published). Events are
noticed by a Prisma client extension so every write path is covered,
re-checked before sending, and delivered as signed JSON
(X-CrossEvents-Signature, HMAC-SHA256) with retries, a 30-day delivery
log, Send test and Resend. Public https addresses only; each endpoint
is added to the operator register; kids and volunteer tickets are never
sent. New `webhooks` job. Migration 20261028160000_webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:00:59 +02:00
joshua 50e0cbe62d Merge branch 'fix/update-request-newer' 2026-10-28 12:16:56 +02:00
joshuaandClaude Opus 5.5 e66d39f6ff Fix: update request for an older version than the latest (1.47.4)
After asking for an update, a newer version coming out made the Licence
page claim the newer version was requested, with no way to ask for it.
Now it shows the version asked for, that a newer one is out, and "Ask
for X instead"; the banner shows again. Hub 1.5.0 moves the open request
on (`changed`); with an older Hub the site withdraws and asks again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:16:56 +02:00
joshua 8ec5dcefb9 Merge branch 'feat/season-pass' 2026-10-28 11:19:58 +02:00
joshuaandClaude Opus 5.5 cf7d00bdf3 Season passes (1.47.3)
A pass sells a ticket at each of several events in a series for one
price. Supervisors set passes up on the Event series page (events and
ticket per event; fixed once sold). Buying on the series page registers
the buyer at every event at once with one checkout (free passes give
tickets straight away; Pay now if online payment isn't possible). The
price is split over the events in proportion to their normal prices:
each registration line is priced at its share and the webhook records
one Payment per event, so cashups stay per event. Pass registrations
aren't repriced, take no coupons and can't be edited. Migration
20261028150000_season_pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:19:58 +02:00
joshua 24cd604b43 Merge branch 'feat/series-reports' 2026-10-28 10:57:04 +02:00
joshuaandClaude Opus 5.5 bc8021cde0 Series: year on year report (1.47.2)
New report (Reports -> Other, or "Compare" on the Event series page):
each event in a series side by side, oldest first - registrations,
tickets, income (dashboard definition), people checked in (average per
session on multi-session events) and attendance rate, with the change
from the event before. Exports like the other reports; campus-scoped
staff see only their campuses' events. GET /api/series/:id/compare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:57:04 +02:00
joshua e221d83ff8 Merge branch 'feat/event-series' 2026-10-28 10:29:59 +02:00
joshuaandClaude Opus 5.5 164c74e5dd Event series (1.47.1)
Group separate events (Camp 2025, Camp 2026) on a series page at
/series/<slug> with upcoming and past events. Events join a series from
the event editor (copies keep it); a series can span campuses. Event
pages show "Part of ..." and "Next in this series". Signed-in people can
follow a series; the new `series` job emails followers once when a new
event in it goes live, as News & announcements (opted-in only, with
unsubscribe). Follows are in the data export and removed on
anonymising. Migration 20261028140000_event_series.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:29:59 +02:00
joshua 6bdf33b0e5 Merge branch 'feat/event-clone' 2026-10-28 10:01:18 +02:00
joshuaandClaude Opus 5.5 7148051896 Copy an event (1.47.0)
"Copy" on each event card opens the event editor filled in from that
event (campus, sessions, options, variants, early birds, sections, form,
recipients, feedback questions, certificates, reminders). "New start"
moves every date with it. Allocation groups and, for admins, planned
costs are copied by POST /api/events/:id/copy-from. Registrations,
coupons, attachments, kids check-in and volunteer roles are not copied.

Roadmap: event series and cloning ships as 1.47.0-1.47.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:01:17 +02:00
joshua ddf5290bbd Merge branch 'chore/whats-new-history' 2026-10-28 09:25:08 +02:00
joshuaandClaude Opus 5.5 1b5a967acf WHATS-NEW.md: church-facing notes for every version back to 1.0.0
The Hub reads this file from main (Hub 1.4.1), so these show on sites' Licence
page without a new release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:25:08 +02:00
joshua ae0458bf8f Merge branch 'chore/licence-updates' 2026-10-28 09:13:30 +02:00
joshuaandClaude Opus 5.5 443b73773d WHATS-NEW.md for churches; docs, changelog (1.46.2)
Client-facing release notes the Hub reads from git with the version tags, so
the latest version and its notes reach installs without touching the Hub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:13:30 +02:00
joshuaandClaude Opus 5.5 a9baa3b127 Licence page: what's new, withdraw request, Not now, provider notices
- Site settings -> Licence shows the release notes for every newer version from
  the Hub; urgent (security/serious) updates are marked and can't be put off.
- Withdraw an update request (the provider is told through the Hub).
- "Not now" on the banner or Licence page hides update reminders until the
  next version.
- Notices from the provider show as a dashboard banner for site admins and
  supervisors, in their time window, and on the Licence page.
- New audit actions (migration), API docs, help, protocol doc, tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:54:35 +02:00
joshua 44af96c0ee Merge branch 'chore/remove-ci' 2026-10-28 08:15:45 +02:00
joshuaandClaude Opus 5.5 d6d7cdf56d Remove the Gitea CI workflow; docs, changelog (1.46.1)
There's no Actions runner (no machine that can run Docker), so every push
left a run stuck on "Waiting". Tests and lint are run by hand before a
release, and releases are deployed with scripts/deploy.sh on the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:15:44 +02:00
joshua 6bc7a7ec22 Merge branch 'feat/volunteer-rosters' 2026-10-28 03:59:52 +02:00
joshuaandClaude Opus 5.5 e11c3caaab Volunteer rosters: docs, changelog (1.46.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00
joshuaandClaude Opus 5.5 4166096706 Volunteer rosters: serving, roster and check-in pages, help, e2e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00
joshuaandClaude Opus 5.5 a9f13a1b0a Volunteer rosters: roles, sign-ups, swaps, QR check-in, kids-room duty (backend)
Serving roles per event or session, sign-ups and assigning with an overlap
check, swaps that happen on accept (notify recipients emailed), QR and manual
check-in (kids-room roles start rostered duty), optional free volunteer ticket,
day-before reminder job, hours served, privacy hooks. The kids check-in and
volunteer tickets are left out of public event pages and public registration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00
joshua a4fc2c0a88 Merge branch 'fix/legal-pages' 2026-10-28 01:09:51 +02:00
joshuaandClaude Opus 5.5 4515fde7aa Privacy notice and terms of use brought up to date (1.45.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMccH2LkkfYmsSLwPaq
2026-10-28 01:09:51 +02:00
joshua 2f550bc9e8 Merge branch 'feat/kids-check-in' 2026-10-28 01:01:09 +02:00
joshuaandClaude Opus 5.5 b6a0d49c5c Kids check-in: docs, changelog (1.45.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 01:01:08 +02:00
joshuaandClaude Opus 5.5 f9de6b84ee Kids check-in: desk, room screen, setup and parent pages, help, e2e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 01:01:08 +02:00
joshuaandClaude Opus 5.5 115dbb177f Kids check-in: families, pickup codes, rooms, check-in/out, offline sync (backend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:46:41 +02:00
joshuaandClaude Opus 5.5 b28434f2e2 Roadmap: kids check-in fully digital, wallet passes removed from scope
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:29:10 +02:00
joshua 2ed9f4bbc1 Merge branch 'feat/campus-scoped-staff' 2026-10-27 22:59:00 +02:00
joshuaandClaude Opus 5.5 116a2ce4b4 Campus-scoped staff: help, docs, changelog (1.44.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:52:11 +02:00
joshuaandClaude Opus 5.5 193cf4267a Campus-scoped staff: frontend and e2e
Admin -> Users 'Limit to campuses'; staff campus pickers, reports, dashboards
and audience picker follow the scope (useMyCampuses); scoped people pick one
of their campuses for new events, and church-wide / other campuses' events
open read-only; 'You work with ...' note; warning before turning campuses off
while staff are limited. e2e: scanner refusal naming the campus, scoped
events list and read-only editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:50:03 +02:00
joshuaandClaude Opus 5.5 f8a567615c Campus-scoped staff: admins set limits; profile returns the scope
PUT /api/users/:id takes scopedCampusIds (supervisors/staff only, audited as
user_campus_scope_changed); GET returns scopedCampuses; the profile returns
campusScope (null when unscoped or campuses are off).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:40:32 +02:00
joshuaandClaude Opus 5.5 fd1cbb3239 Campus-scoped staff: every staff/supervisor route checked
Events, payments, registrations, scan locks and tickets marked; list
controllers filtered (registrations, payments, tickets, scans, stats,
coupons, scheduled messages, form responses, funnel). Owner-or-staff routes
check staff against the record's event (ownerOk). Scanner names the campus
of another campus's ticket. Route test passes; unit tests for the rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:37:42 +02:00
joshuaandClaude Opus 5.5 2ac2ec36e0 Campus-scoped staff: schema, campusScope helper, route test, first 79 routes
UserCampusScope relation and audit action; scopeEvent/scopeList/unscopedOnly/
campusIndependent/scopeBroadcast markers; tests/campusScopeRoutes.test.js
(still failing: events, payments, registrations, scan locks, tickets left).
Can't delete a campus that has scoped staff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:28:30 +02:00
joshuaandClaude Opus 5.5 ab4152960b Roadmap: 1.44.0 campus-scoped staff decisions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:17:32 +02:00
joshua eff2cb108b Merge branch 'feat/campuses' 2026-10-27 16:56:07 +02:00
joshuaandClaude Opus 5.5 7e8eeaa7a5 Campuses frontend, docs and e2e (1.43.0)
Site settings -> Campuses tab; campus picker in the event editor; campus
filter and badges on the events list, public events page (remembered,
starts on home campus) and reports/dashboards; /campus/<slug> pages and
sitemap; home campus on the profile; "Everyone at a campus" in email and
WhatsApp broadcasts. Help, FEATURES, SETTINGS, API docs, protocol doc
(campusCount), handover and roadmap updated; campuses seeded for e2e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:45:43 +02:00
joshuaandClaude Opus 5.5 e138d4811d Campuses backend: model, admin/public API, events per campus, filters
- Campus model, Event.campusId (null = all campuses), User.homeCampusId,
  per-campus summary recipients; campuses_enabled setting (off by default)
- /api/campuses: public list and landing page, admin CRUD/order/archive,
  "everyone at campus X" audience (home campus + optional 12-month registrants)
- Events: campus on create/update (audited when moved), ?campus= on the
  public list (with church-wide events) and staff list; campus included
- Home campus on the profile; cleared when anonymising
- Overview stats ?campus= filter; campus summary recipients; campus on
  ticket PDFs; heartbeat reports the real campus setting
- Migration also adds hub_update_requested, missing since 1.42.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:23:33 +02:00
joshua 388ba26c33 Merge branch 'docs/multi-campus-plan' 2026-10-27 16:09:06 +02:00
joshuaandClaude Opus 5.5 07f5dc1969 Roadmap: split multi-campus into 1.43.0 campuses and 1.44.0 scoped staff
Records the decisions: scoped staff view and scan "All campuses" events but
can't edit them; "everyone at campus X" is home campus plus optional recent
registrants; campus landing pages in 1.43.0. Later phases move up by one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:09:04 +02:00
joshua 8e63639713 Merge branch 'fix/hub-public-key' 2026-10-27 14:28:49 +02:00
joshuaandClaude Opus 5.5 3bbaacbac1 Build the production Hub public key in (1.42.1)
PRODUCTION_PUBLIC_KEY is the key the production Hub serves at
/api/public-key, normalised to PEM, so installs no longer need
HUB_PUBLIC_KEY. Test covers the built-in key with the env var unset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:28:48 +02:00
joshua 4f40ef195f Merge branch 'docs/handover-roadmap' 2026-10-27 14:03:01 +02:00
joshuaandClaude Opus 5.5 c2034fd523 Handover and roadmap: Cross Events rename, Request update, versions moved up
1.41.3 and 1.42.0 / Hub 1.1.0 recorded; Multi-campus is now 1.43.0 and
later phases move up by one. Next steps: roll out update requests, build
the Hub public key in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:03:00 +02:00
joshua b33936eac0 Merge branch 'feat/request-update' 2026-10-27 13:55:06 +02:00
joshuaandClaude Opus 5.5 f37ec5c8ef Request update button instead of the deploy command (1.42.0)
Site settings -> Licence sends a signed update request to the Hub
(docs/hub-protocol.md 3a) instead of showing bash scripts/deploy.sh. Shows
"Update requested" until the site runs that version and hides the update
banner meanwhile. Audit-logged as hub_update_requested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:55:05 +02:00
joshua c777515025 Merge branch 'fix/cross-events-name' 2026-10-27 13:06:22 +02:00
joshuaandClaude Opus 5.5 a238e7fc22 Bump to 1.41.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:06:21 +02:00
joshuaandClaude Opus 5.5 0367e0ca6d Rename the product to Cross Events in UI text and docs
Display text only: storage keys, slugs, the encryption salt, the repo URL
and applied migrations keep their old names so existing installs keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:06:20 +02:00
joshua afe1e25cde Merge branch 'docs/frp-deployment' 2026-10-27 12:11:14 +02:00
joshuaandClaude Opus 5.5 3091783bdd Deployment guide for installs behind an frp tunnel
DEPLOYMENT.md: install with --no-ssl, switch URLs to https, TRUST_PROXY,
nginx and /etc/frp/frpc.ini for TLS on the VPS or in frpc (https2http),
checking visitor IPs, updates and troubleshooting. Linked from the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:11:11 +02:00
joshua a47c04e4a4 Merge branch 'fix/job-times' 2026-10-27 11:06:54 +02:00
joshuaandClaude Opus 5.5 2ca48a3d06 Bump to 1.41.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:06:54 +02:00
joshuaandClaude Opus 5.5 e16c7ee09d Background jobs: show last-run times in the right time zone
pg-boss timestamps are timestamptz, and Prisma's pg adapter drops the offset in raw queries (10:55+02 came back as 10:55Z, shown as 12:55). Read them AT TIME ZONE 'UTC'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:06:51 +02:00
joshuaandClaude Opus 5.5 b2b126068a Document APP_TIMEZONE in .env.example and SETTINGS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:49:16 +02:00
joshua 95401baff7 Merge branch 'fix/licence-checks' 2026-10-27 10:45:41 +02:00
joshuaandClaude Opus 5.5 b495fb8d36 Bump to 1.41.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:45:40 +02:00
joshuaandClaude Opus 5.5 d1d6c90821 Licence: no licence is read-only, editing events blocked, heartbeat 30 s after start
- A site the Hub answers INSTALL_NOT_FOUND for drops its install and licence, so it
  no longer shows "Active" on the old token.
- Unlicensed is read-only like suspended; read-only also blocks editing events,
  options and variants. LICENCE_CHECK_DISABLED (ignored in production) for e2e.
- Heartbeat 30 s after the server starts and after a licence key is connected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:45:38 +02:00
joshua 1adf6e426d Merge branch 'feat/hub-client' 2026-10-26 13:03:53 +02:00
joshuaandClaude Opus 5.5 1fe9048aa2 Bump to 1.41.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 13:03:53 +02:00
joshuaandClaude Opus 5.5 51ad8f0bb0 Handover and roadmap: 1.41.0 and Hub 1.0.0; next steps to go live
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 13:03:50 +02:00
joshuaandClaude Opus 5.5 ff98a6fdfd Hub client: accept the public key pasted on one line; clearer error for a bad key
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 12:58:44 +02:00
joshuaandClaude Opus 5.5 b67f40c2df Hub client: licence, heartbeat, read-only mode, /health, install script
- Connect with a licence key (/setup last screen, Site settings -> Licence)
- hub-heartbeat job every 15 min: version, health, totals (income as a band)
- Licence tokens verified with the Hub's public key; states active / grace
  (banner for site admins only) / suspended / revoked (read-only) /
  unlicensed; Hub keys kept out of the generic settings endpoints
- /health; "update available" for admins; scripts/install.sh
- docs/hub-protocol.md shared with the events-hub repo
- Unit tests (hub.test.js); docs

The production Hub public key (backend/src/hub/publicKey.js) must be set
before this is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 12:25:52 +02:00
joshua 9960c4e938 Merge branch 'docs/hub-repo' 2026-10-24 16:03:43 +02:00
joshuaandClaude Opus 5.5 e07d62a125 Roadmap: Hub repo is joshua/events-hub; grace banner for site admins only
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-24 16:03:43 +02:00
joshua 7e4b657f41 Merge branch 'docs/ai-roadmap' 2026-10-24 14:36:25 +02:00
joshuaandClaude Opus 5.5 8146628627 Roadmap: AI helpers as the 2.0 headline, and later AI stages
- §15 AI helpers (2.0): one-button helpers (draft an event, summarise
  reports and feedback, draft messages, improve text) on Claude Haiku 5.5,
  called through the Hub, which holds the key, meters usage in rand and
  enforces a monthly cap per licence; admin usage view; POPIA notes
- §16 AI later stages (unversioned): Ask AI, help/navigation assistant,
  actions with confirmation, more helpers, long-term self-hosted AI
- Hub: AI cap as the first per-licence limit, AiUsage model; decisions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-24 14:36:25 +02:00
joshua 11528d2239 Merge branch 'feat/popia-retention' 2026-10-23 20:26:01 +02:00
joshuaandClaude Opus 5.5 9ac63e2406 Bump to 1.40.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 20:26:01 +02:00
joshuaandClaude Opus 5.5 6907bc3bd3 POPIA toolkit part 3: retention, breach register, readiness
- Retention policies (Admin -> Privacy -> Retention) applied by a nightly
  `retention` job: inactive accounts anonymised after 5 years with a
  30-day warning (on by default; never staff roles or people with an
  upcoming registration), form answers, login history, payer details in
  payment notifications, audit/access logs
- User.lastLoginAt (set on login, backfilled) and inactivityWarnedAt
- Breach register (SecurityBreach) with drafts for the people affected
  and the Information Regulator
- Readiness checklist with a score
- Children's/medical flag in the access log; {retention} placeholder in
  the privacy notice
- Unit tests (retention.test.js), e2e (privacy-retention.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 20:25:58 +02:00
joshua 7f5e31461a Merge branch 'feat/popia-admin-tools' 2026-10-23 19:11:23 +02:00
joshuaandClaude Opus 5.5 91cb7ddc6f Bump to 1.39.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 19:11:23 +02:00
joshuaandClaude Opus 5.5 34f9e96e4e POPIA toolkit part 2: privacy notice editor, operators, consent and access logs
- Admin -> Privacy (POPIA): edit the privacy notice (built-in text as the
  start, placeholders for org/IO/operators), drafts, preview, numbered
  versions; earlier versions readable on /legal/privacy?version=N
- "Significant change" versions are accepted once after login
  (NoticePrompt); sign-up records the version accepted
- Operator register (seeded with the services the app uses), listed in
  the notice via {operators}
- Consent log (news opt-ins, notice acceptances, parental consent) and
  access log (report exports, registers, certificates, group lists, form
  answers, consent/medical lists, backups, impersonation)
- Information Officer on the contact page
- Unit tests (privacyNotice.test.js), e2e (privacy-notice.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 19:11:20 +02:00
joshua 04be99b930 Merge branch 'feat/popia-privacy-centre' 2026-10-23 18:24:07 +02:00
joshuaandClaude Opus 5.5 3201397f2c Bump to 1.38.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 18:24:07 +02:00
joshuaandClaude Opus 5.5 18f35ceeb3 POPIA toolkit part 1: privacy page, unsubscribe, WhatsApp STOP, data requests
- Privacy page: news opt-in per channel with history, download my data
  (JSON + PDF), correction and deletion requests
- Bulk messages are an Event update or News & announcements; news only
  reaches people who opted in, with unsubscribe links, one-click
  List-Unsubscribe headers and "Reply STOP" on WhatsApp
- WhatsApp STOP via WAWP's message webhook, checked against a secret in
  the webhook URL
- Sign-up opt-in box; existing accounts kept opted in and asked once
- Admin -> Data requests with 30-day due dates and a daily reminder job
- Deleting an account is a request; anonymising now covers attendees,
  form answers, consent details, payer details in provider payloads, etc.
- Unit tests (privacy.test.js) and e2e (privacy.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 18:13:47 +02:00
joshua f03b766b6e Merge branch 'fix/deploy-script' 2026-10-23 16:20:22 +02:00
joshuaandClaude Opus 5.5 8654473679 Deploy script: roll back once (not inside subshells); docs; bump to 1.37.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:20:22 +02:00
joshuaandClaude Opus 5.5 d0589de592 Deploy: latest main without a tag; per-install PM2 config out of git
- scripts/deploy.sh with no tag deploys the latest main (detached
  origin/main); with a tag, that release.
- ecosystem.config.js is no longer in git (now ecosystem.config.example.js;
  the deploy creates the install's copy from it once). The deploy keeps the
  install's copy safe across checkouts and rollbacks, including releases
  that still tracked it.
- The script runs from a temp copy, so checking out a new deploy.sh can't
  change it mid-run; set -E so failures in functions still roll back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:15:29 +02:00
joshua 39ba82d63b Merge branch 'fix/help-entities' 2026-10-23 15:57:46 +02:00
joshuaandClaude Opus 5.5 569824a75d Fix the production build: escape quotes in the Payments help text
The deploy's next build fails on react/no-unescaped-entities. Bump to
1.37.3; the handover now says to lint the whole frontend before tagging.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:57:46 +02:00
joshua eeb929d931 Merge branch 'feat/payment-status' 2026-10-23 15:28:31 +02:00
joshuaandClaude Opus 5.5 966cf5eb1c Bump to 1.37.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:28:31 +02:00
joshuaandClaude Opus 5.5 2064ba2e42 Payment status checks for notifications that never arrive
- src/payments/status.js: open checkouts, checkCheckouts and the
  payment-status job (every 15 min, checkouts 10 min - 3 days old). Found
  payments are settled exactly as their webhook would be (settlePayment,
  extracted from the webhook handler: amount check, record, emails).
- PayFast: signed API client (alphabetical signature, testing=true in
  sandbox), findPayments from the transaction history CSV matched on
  M Payment ID, and testConnection (signed /ping). Verified against a
  real sandbox account.
- Yoco documents no checkout lookup, so its checkouts are "can't check".
- Payments -> Reconcile: "Waiting for payment" with Check status /
  Check all; PayFast card: Test connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:28:28 +02:00
joshua 67730d3eb0 Merge branch 'feat/hide-pay-online' 2026-10-23 15:05:01 +02:00
joshuaandClaude Opus 5.5 4c58b9457a Bump to 1.37.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:05:01 +02:00
joshuaandClaude Opus 5.5 fcb7a00121 Hide "Pay online" when no provider is on or the amount is under R15
A shared useOnlinePayments hook (GET /api/payments/providers) gates the
registration success page, My Events (Make payment, Make donation), the
donate page, Sponsor a spot, the register form's donation box and the
supervisor Payment Link tab; they explain why where it helps.

Roadmap: SnapScan and Zapper dropped; later versions move up by two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:04:58 +02:00
joshua e91a538ced Merge branch 'feat/payfast' 2026-10-23 14:26:09 +02:00
joshuaandClaude Opus 5.5 c9785efa7e Bump to 1.37.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:26:09 +02:00
joshuaandClaude Opus 5.5 228719ef96 PayFast provider, Pay online page, amount checks on payments
- PayFast (custom integration): signed form (PHP-style encoding, checked
  against a real sandbox), ITN checks (signature over all posted fields,
  PayFast host, VALID from /eng/query/validate, amount vs checkout).
- ProviderCheckout records every checkout (amount, metadata, request);
  webhooks match payments to it and hold a different amount for review
  (ProviderTransaction.note).
- /pay/<id>: payers choose a provider when several are on, and the
  browser posts PayFast's form from there, so payment links work for
  every provider.
- Site settings → Payments: PayFast card (merchant ID/key, encrypted
  passphrase, sandbox/live) while PayFast is enabled.
- Payer-facing wording no longer names Yoco; legal pages name both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:25:49 +02:00
joshua 1fc5e44183 Merge branch 'feat/payment-providers' 2026-10-23 12:17:56 +02:00
joshuaandClaude Opus 5.5 15e9b6faf0 Bump to 1.36.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:17:56 +02:00
joshuaandClaude Opus 5.5 2116d727b9 Payment provider interface: Yoco behind it, Site settings → Payments
- src/payments: provider registry and PaymentProvider interface
  (createCheckout, verifyWebhook/parseWebhook, getTransaction, refund,
  listTransactions as capabilities), Yoco as the first provider. All four
  direct Yoco checkout calls go through payments.createCheckout.
- Webhook split into the provider part (signature, parsing) and shared
  processing; same URL (/api/webhooks/yoco), same behaviour.
- YocoTransaction renamed in place to ProviderTransaction (+ provider,
  unique per provider + externalId); Payment.provider added and
  backfilled to "yoco". Payment.method stays the wallet type so cashups
  are unchanged.
- Site settings → Payments: Enabled toggle and order per provider; Yoco's
  settings shown while it's enabled. R15 minimum for all online payments.
- New endpoint names (/api/payments/checkout, /api/provider-transactions);
  the old /yoco-checkout and /yoco-transactions paths still work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:17:29 +02:00
joshua 608f3ccec5 Merge branch 'feat/session-gaps' 2026-10-23 11:38:43 +02:00
joshuaandClaude Opus 5.5 c0ed63a885 Bump to 1.35.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:38:43 +02:00
joshuaandClaude Opus 5.5 e368be4dce Session gaps: per-session waitlist, door session picker, all-sessions choice
- Waitlist per session: entries for pick-sessions tickets name a session;
  offers use that session's free places, never run past its start, and
  claim links tick it. Held offers count towards session capacity.
- At the door: the Select items pop-up has the session picker, with
  today's session preselected for new attendees.
- On pick-sessions events every ticket shows the session list straight
  away. "All sessions" tickets record the ticked sessions
  (RegistrationOption.sessionIds) at one price; scanning, attendance,
  certificates, reminders and capacity follow them.
- Fix: per-session stock limits weren't enforced (takenCount filtered
  WaitlistEntry by a sessionId column that didn't exist, and the error
  was swallowed), and the public event page lost its stock info.
- Fix: editing a door registration with picked sessions couldn't be saved.
- Fix: the offline-scanning service worker served /_next/static cache-first
  forever, so dev browsers that had opened the scanner ran stale code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:38:21 +02:00
joshua f6d19a596e Merge branch 'feat/pick-sessions' 2026-10-23 09:25:35 +02:00
joshuaandClaude Opus 5.5 c207ea417a Bump to 1.35.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:25:32 +02:00
joshuaandClaude Opus 5.5 abf9ca714d Pick sessions (frontend), roadmap and handover docs
Event wizard: how people book (whole course / pick sessions), capacity
per session and per-option session mode. Session picker on the public
registration page, Manual registration and the kiosk; at the door points
to Manual registration. Register, tickets and My Events handle picked
sessions. Adds docs/ROADMAP-v2.md and docs/HANDOVER.md so work can carry
on from another machine, and a pick-sessions e2e test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:25:21 +02:00
joshuaandClaude Opus 5.5 e22566bdeb Pick sessions (backend): book individual sessions with per-session capacity
Options on a multi-day event can be bought per session (one line and
ticket per session, priced per session, bookable until the session
starts). Sessions can have a capacity covering picked places and
whole-course tickets. Picked tickets only scan on their own session; the
register, certificates and reminders follow the sessions booked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:05:48 +02:00
joshua 6a8bc6f9dd Merge branch 'feat/ci-e2e-jobs' 2026-10-22 15:50:00 +02:00
joshuaandClaude Opus 5.5 dd6fe949b7 Bump to 1.34.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:49:56 +02:00
joshuaandClaude Opus 5.5 3f12efc1d4 Run background jobs on a pg-boss queue; add e2e tests, CI and deploy script
Timed jobs move from in-process timers to a job registry run by pg-boss:
once per schedule across processes, retries, run history, cron schedules
in the church timezone, and an admin Background jobs page with Run now.
Playwright end-to-end tests run against their own seeded database. A
Gitea Actions workflow runs backend tests, frontend checks and the e2e
tests, and deploys v* tags with scripts/deploy.sh once secrets are set.
Also fixes the at-the-door check-in count for multi-day tickets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:49:46 +02:00
joshua 60d522c3a9 Merge branch 'feat/multi-day-sessions' 2026-10-22 14:54:03 +02:00
joshuaandClaude Opus 5.5 0c10bda057 Bump to 1.33.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:53:59 +02:00
joshuaandClaude Opus 5.5 f4b358e5c8 Add multi-day events (frontend), attendance register and certificates
Event wizard: one date or multiple sessions with a repeat-pattern builder,
and a new Attendance step (late joining and pricing, check-in window,
session reminders, certificates with preview). Public pages show the
schedule and late prices; the scanner picks today's session; new
attendance register page, My Certificates, and a public verify page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:53:39 +02:00
joshuaandClaude Opus 5.5 623c85ccc5 Add multi-day event sessions (backend)
Events can run over several sessions: per-session check-in with a whole-day
or session-time window, late joining with pro-rata or fixed late pricing,
an attendance register (Excel/PDF), session reminders, and completion
certificates (four templates, public verify page).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:20:52 +02:00
joshua 65986342b3 Merge branch 'feat/early-bird-ribbon' 2026-10-22 13:48:29 +02:00
joshuaandClaude Opus 5.5 da461bbc96 Bump to 1.32.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:48:28 +02:00
joshuaandClaude Opus 5.5 bcd3de94b4 Show an early-bird ribbon on event cards
Event cards on the home page and events list get a diagonal "Early bird"
ribbon in the top-right corner while an early-bird tier is running and
registration is open. GET /api/events returns earlyBirdEndsAt per event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:48:22 +02:00
joshua 49c379a13e Merge branch 'feat/google-site-verification' 2026-10-22 11:43:01 +02:00
joshuaandClaude Opus 5.5 896d533736 Bump to 1.31.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:43:00 +02:00
joshuaandClaude Opus 5.5 0ae5afabd4 Add Google Search Console verification setting
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:42:56 +02:00
joshuaandClaude Opus 5.5 6fb1866f41 Merge branch 'feat/seo-and-traffic-sources'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:26:17 +02:00
joshuaandClaude Opus 5.5 92903e35d8 Bump to 1.31.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:26:15 +02:00
joshuaandClaude Opus 5.5 866b340a4e Add event structured data, canonical URLs and referrer-based traffic sources
- Event pages emit schema.org Event JSON-LD (dates, venue, image,
  organizer, ZAR offers, sold-out status) for Google event results.
- Event pages, the events list and home page set a canonical URL so
  tagged and alias links don't split rankings.
- Funnel tracking falls back to the referring site (Facebook, Instagram,
  Google, ...) and fbclid/gclid when a link has no utm_source/src.
- Share and Save QR on the event page tag their links as share / qr.
- getServerSettings moves to lib/serverSettings.ts for reuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:26:02 +02:00
joshuaandClaude Opus 5.5 2dff048d12 Merge branch 'feat/unified-ticket-design'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:59:24 +02:00
joshuaandClaude Opus 5.5 c4c18140ed Bump to 1.30.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:59:21 +02:00
joshuaandClaude Opus 5.5 6c555525c7 Use the dashboard ticket design for all tickets
The emailed/WhatsApp ticket PDF and the staff and at-the-door print
views now match the user dashboard's printed tickets: rounded cards with
a light border and soft shadow. Printing goes through a shared helper in
lib/ticketPrint.ts, which also escapes names in the print HTML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:59:07 +02:00
joshuaandClaude Opus 5.5 b2a7996e6d Merge branch 'feat/registration-donation'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:29:17 +02:00
joshuaandClaude Opus 5.5 a6387ba79b Bump to 1.30.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:29:11 +02:00
joshuaandClaude Opus 5.5 eadd9a8329 Add optional donation to registration; fix soldOutLines server crash
The register form now offers a "Donation amount" (suggested amounts,
custom, or none) under the ticket options. The donation is added to the
Yoco checkout as its own line and the webhook records it as a separate
donation payment linked to the registration payment.

Move soldOutLines() out of the "use client" JoinWaitlistButton module
into lib/waitlist.ts so the server-rendered event page can call it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:27:47 +02:00
joshuaandClaude Opus 5.5 0aabc03fe6 Bump to 1.29.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:36:17 +02:00
joshuaandClaude Opus 5.5 88f3014750 Merge branch 'feat/coupons-redesign'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:36:16 +02:00
joshuaandClaude Opus 5.5 ebd3e1f951 Redesign the Coupon codes page to match Bundle deals
Cards instead of the table, phone-friendly sheets for the form and the uses list,
inactive codes hidden by default, and the events picker shows upcoming events only
(with search and a Show past events option).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:36:16 +02:00
joshuaandClaude Opus 5.5 c98545b5e4 Bump to 1.29.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:21:05 +02:00
joshuaandClaude Opus 5.5 3bc9704769 Merge branch 'feat/bundle-types'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:21:05 +02:00
joshuaandClaude Opus 5.5 3369794097 Add bundle types: pick any, buy X get Y free, group discount
Bundles get a kind: exact (as before), mix (any setSize of the qualifying tickets for
a set price), free (cheapest freeCount in each set free) and group (setSize or more
qualifying tickets at a per-ticket price or % off, applied once). The supervisor page
has a type picker, buyers see a one-line description of each deal, and the Complete
bundle cards handle every type. Demo: Family Fun Day adds a Lunch for four deal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:21:05 +02:00
joshuaandClaude Opus 5.5 44d18cbdd6 Bump to 1.28.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:03:22 +02:00
joshuaandClaude Opus 5.5 454868a6bf Fix the bundle edit form's ticket rows
The quantity input had both w-full and w-16; w-full won, filling the row and pushing
the ticket picker off the side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:03:21 +02:00
joshuaandClaude Opus 5.5 f84d57a5b4 Bump to 1.28.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:56:04 +02:00
joshuaandClaude Opus 5.5 5805a65d3b Redesign the Bundle deals page
Upcoming events only by default (with a Show past events option), bundles as cards
instead of a table, and a mobile-friendly edit form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:56:03 +02:00
joshuaandClaude Opus 5.5 0368b7ee86 Add bundle deals to manual registration
Lists the event's deals and shows the Complete bundle / + cards, as at the door and
on the kiosk. Part of 1.28.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:32:17 +02:00
joshuaandClaude Opus 5.5 a7954837f0 Bump to 1.28.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:22:49 +02:00
joshuaandClaude Opus 5.5 2c2acc49e4 Merge branch 'feat/bundles-door-kiosk'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:22:48 +02:00
joshuaandClaude Opus 5.5 a513f893d0 Add bundle deals to at the door and the kiosk
Both list the event's deals and show the Complete bundle / + cards from the register
form. At the door gets the standard Back to dashboard link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:22:48 +02:00
joshuaandClaude Opus 5.5 125c2e7f53 Bump to 1.28.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:14:53 +02:00
joshuaandClaude Opus 5.5 981056a045 Merge branch 'feat/bundle-deals'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:14:53 +02:00
joshuaandClaude Opus 5.5 268781d610 Add bundle deals
Sell a set of tickets together for one price (e.g. 5 Adult + 3 Child for R500).
Bundles apply automatically, as many times as a registration's tickets allow, and
only when cheaper than the prices actually charged. Coupons come off afterwards.

- EventBundle/EventBundleItem/RegistrationBundle models and Registration.bundleDiscount
- Supervisor "Bundle deals" page, quote endpoint, bundle lines on invoices,
  receipts, emails, WhatsApp and Yoco checkout, Discounts report rows
- Register form shows started bundles with "Complete bundle" and "+" buttons
- Demo: Family Fun Day sells a Family deal bundle instead of the Family pass ticket

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:14:53 +02:00
joshuaandClaude Opus 5.5 2a8e8c7c11 Bump to 1.27.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:39:48 +02:00
joshua 988b23ec73 Merge branch 'chore/demo-history' 2026-10-21 13:39:47 +02:00
joshuaandClaude Opus 5.5 9bf2fb594c Add ten completed events to the demo data
set-demo now also stages ten past events with door sales, staff cash
counts, check-ins, refunds, donations and feedback. Their cashups run
through the real cashup code after the insert and cover every path:
quick close, full settlements (card fees, deposit fee, shortfall, cash
on hand, an unaccounted amount), close-reopen-close, and pending EFT
money received later or still outstanding. One recent event is left
open with the cash counted for a live demo. Funnel sessions older than
90 days are rolled up into daily totals, as the app does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:39:47 +02:00
joshuaandClaude Opus 5.5 f0313cd346 Bump to 1.27.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:29:29 +02:00
joshua 8270fa2cc3 Merge branch 'feat/cashup-settlement' 2026-10-21 13:29:28 +02:00
joshuaandClaude Opus 5.5 6725005c86 Take cash deposit fees out of the counted cash
A bank charge on a cash deposit comes out of cash that was counted and
banked, so cash on hand is now the count less what reached the bank and
any bank-charge write-off. Before, a deposit fee showed as money "more
than expected".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:29:17 +02:00
joshuaandClaude Opus 5.5 7eb3744ec5 Add cashup settlement and back links to the changelog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:19 +02:00
joshuaandClaude Opus 5.5 1d8f5616c8 Settle cashups: where the money ended up
A full cashup now records, per payment method, how much of the expected
takings is in the bank, still on hand (cash) or pending (on the card
report or with a POP), and writes off what was lost to card fees, bank
charges or a shortfall. Whatever is left is shown as unaccounted; closing
with an unaccounted amount is allowed after a warning.

Pending money can be marked received or written off after the event is
closed, without reopening it. Reopening starts the next cashup from the
last one. Write-offs come off net profit and show as "Bank & card
charges" in the cashup, finance and profit reports.

The reports page also moves to the shared back link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:04 +02:00
joshuaandClaude Opus 5.5 724424246c Use one back link style across the dashboards
Every dashboard page now uses the shared BackLink, the small
"← Back to dashboard" link above the page title that the Waitlist page
already had, instead of a mix of grey Back buttons in different places.
Pages that had no way back (site settings, profile, donate, manual
registration) get one too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:04 +02:00
joshuaandClaude Opus 5.5 fc9e6e1277 Bump to 1.26.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:23:51 +02:00
joshua 056a1ba4af Merge branch 'chore/demo-data' 2026-10-21 12:21:03 +02:00
joshuaandClaude Opus 5.5 f341cc1d06 Add set-demo script for staging demo data
npm run set-demo wipes the database, keeping the site settings and the
admin account, and stages six upcoming events with registrations,
payments, tickets, a waitlist, camp cabins, coupons, costs and funnel
stats for showing the platform to other churches. Documented in
backend/DEMO_DATA.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:21:03 +02:00
joshuaandClaude Opus 5.5 c6628e8a80 Merge branch 'chore/frontend-lint'
Includes chore/deps-security-prisma7 (Prisma 7 upgrade and npm audit fixes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:16:38 +02:00
joshuaandClaude Opus 5.5 2c12c42c3f Bump to 1.26.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:16:38 +02:00
joshuaandClaude Opus 5.5 22e0edca38 Add frontend lint cleanup to the changelog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:11:49 +02:00
joshuaandClaude Opus 5.5 6caf6794fb Type the reports page and turn lint back on in builds
ReportsV2 gets typed API responses (funnel, feedback summary, coupon
redemptions, cashup audit, consent) and derived rows. Master-order
quantities move into a per-row map, so an option name can no longer
overwrite a fixed column. Consent row types move to src/types. Removes
unused export helpers and state.

With the frontend now at zero lint errors and warnings, next build runs
ESLint again (eslint.ignoreDuringBuilds is gone).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 8360a78026 Type the at-the-door page and share pricing helpers
Each door panel and modal gets typed props; unused setError/setInfo/
onCreated props are dropped. The current early-bird price helpers move
to src/lib/pricing.ts (shared with manual registration), dead fallbacks
for a legacy registration 'options' field are removed, and the refund
history now shows a refund's reason (stored in its status field) instead
of a 'reason' field that never exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 5ee1880339 Type payments and user dashboard pages
Moves the duplicated registration-option pricing helper into
src/lib/pricing.ts and drops an unused users list from payments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 d03a5f1493 Type supervisor forms, manual registration and events pages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 f2728892b4 Type registrations, email and WhatsApp messaging pages
Adds typed payloads and results for the email/WhatsApp attendee and
broadcast endpoints. The WhatsApp page's messageDirty flag becomes a ref
(it only gated the template effect), and a no-op branch in the email
template effect is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 b21e7857d0 Type more frontend pages and fix their hook dependencies
Cashup, users, profile, consent, allocations, event options, forms,
event tickets, ticket scanning and manual registration now use real
types. Data loaders are wrapped in useCallback and listed as effect
dependencies. Also adds shared Attendee, Section and form response
types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 dc4d2fff41 Add shared API types and type the smaller frontend pages
Expand src/types with User, Event, EventOption, Registration, Payment,
Ticket, paginated results and dashboard stats, modelled on the Prisma
schema. apiFetch now defaults to unknown instead of any. Dashboard
loaders are wrapped in useCallback so their effects can list them as
dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 5024ab7241 Type caught errors as unknown in the frontend
Replace `catch (e: any)` with `catch (e)` and read the message through a
new errorMessage() helper. ApiError.data gets a real type, and
useDismissingState's setter keeps one identity across renders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:00 +02:00
joshuaandClaude Opus 5.5 9e8244bb71 Fix frontend lint: links, unused code, quotes, img elements
- Internal links use next/link instead of <a> (no full page reload).
- Remove dead code: RegisterForm's unreachable Yoco checkout branch, the
  unused AttendeeForms on the registration success page, unused Geist
  fonts, and assorted unused variables and catch bindings.
- Escape quotes in JSX text; replace @ts-ignore in apiFetch with a cast.
- Keep the intentional raw <img> elements (data URLs, runtime API host)
  with a documented lint exception; the event editor uses ApiImage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:00 +02:00
joshuaandClaude Opus 5.5 700b220906 Upgrade to Prisma 7 and clear npm audit advisories
- Prisma 5.22 -> 7.10 using the @prisma/adapter-pg driver adapter; the
  datasource URL moves to backend/prisma.config.js. All clients are built
  in src/config/db.js, and index.js reuses the shared client.
- Backend: patch follow-redirects, drop nodemon for `node --watch`, and use
  js-yaml 4 for the Jest coverage loader. npm audit reports 0.
- Frontend: override postcss-selector-parser to 7.1.7 (Tailwind 3 output
  is unchanged). braces has no patched release and stays, build/lint only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:58:11 +02:00
joshua 789f59760b Merge branch 'fix/mobile-cookie-banner' 2026-10-20 12:47:41 +02:00
joshuaandClaude Opus 5.5 114ba6af6e Bump to 1.25.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:47:36 +02:00
joshuaandClaude Opus 5.5 5ad0a3d8e3 Lift cookie banner and help button above mobile bottom nav
The cookie consent banner was fixed at bottom-0 under the z-50 BottomNav, so
on mobile it was hidden. It now sits above the nav (h-16 + safe-area) and
publishes its height as --cookie-banner-h, which HelpFab adds to its offset
so the banner no longer covers the help button either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:47:13 +02:00
joshua 9ab446e409 Merge branch 'feat/yoco-settings' 2026-10-20 10:28:57 +02:00
joshuaandClaude Opus 5.5 f263f418b7 Bump to 1.25.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:53 +02:00
joshuaandClaude Opus 5.5 3ee3667886 Store Yoco secrets in the database; add Yoco settings tab
The Yoco secret key and webhook secret now live in AppSetting (AES-256-GCM
encrypted), with .env as a fallback. A new Site Settings → Yoco tab shows
them masked card-style, registers a webhook with Yoco (storing the secret it
returns) or accepts one entered by hand, and lists/deletes the account's
webhooks. Generic settings endpoints never read or write these keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:50 +02:00
joshua 832a2c579e Merge branch 'feat/privacy-transfer-accept' 2026-10-19 18:46:43 +02:00
joshuaandClaude Opus 5.5 d1d417f294 Bump to 1.24.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:46:25 +02:00
joshuaandClaude Opus 5.5 c28cdb28f8 Require acceptance for ticket transfers; privacy and legal updates
Transfers now send the new holder a link (to the email/phone typed) and
only complete once they accept; they can decline and the sender can
cancel. No response reveals whether contact details belong to an
account, and attendee account links are no longer sent to payers.
Terms of Use and Privacy Policy are updated for all features since
1.12, with a full cookie policy and a "Cookie settings" control. The
/docs route list now covers every mounted route, and account
activation auto-login is fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
2026-10-19 18:46:15 +02:00
joshua 1bd976f863 Merge branch 'feat/impersonate-user' 2026-10-19 18:25:10 +02:00
joshuaandClaude Opus 5.5 5bc7019863 Bump to 1.23.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:25:08 +02:00
joshuaandClaude Opus 5.5 bd7e5e8e0e Add read-only admin impersonation
Admins (with 2FA) can view the site as a non-admin user for up to 30
minutes, with a required reason and a "Viewing as" banner. It is
strictly read-only: a guard mounted before every route refuses any
write made with an impersonation token, protect/optionalAuth check the
session is live, and GET handlers skip the price-refresh writes. Start,
end, reason and every page/API call (including blocked attempts) are
audited; optional email to the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
2026-10-19 18:25:02 +02:00
joshua 6b958884d6 Merge branch 'feat/funnel-stats' 2026-10-19 18:14:29 +02:00
joshuaandClaude Opus 5.5 996e0a2d89 Bump to 1.22.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:14:24 +02:00
joshuaandClaude Opus 5.5 904b674378 Add registration funnel stats
First-party, consent-based funnel tracking: a cookie notice asks once,
and only visitors who allow it get an anonymous visit id. Event page
views and registration starts are tracked from the browser; submit and
paid come from the registration. Adds the Registration funnel report
(conversion per stage, daily trend, by source/device/ticket option), a
conversion tile on the supervisor/admin dashboards, short-link source
tagging, and a daily rollup of raw rows older than 90 days.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
2026-10-19 18:14:18 +02:00
joshua 141dce60ee Merge branch 'feat/feedback-forms' 2026-10-19 15:28:48 +02:00
joshuaandClaude Opus 5.5 b82de64d4d Bump to 1.21.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:42 +02:00
joshuaandClaude Opus 5.5 204a4268b6 Add post-event feedback forms
A Feedback step in the event wizard builds a survey that is sent at a
chosen time to everyone who checked in (or everyone registered), with
personal links and one reminder after 3 days. Answers can be anonymous.
Adds rating (1-5 stars) and multiple-choice field types, also usable on
attendee forms, and a Feedback summary report with response rate,
average ratings, choice breakdowns, comments and event comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:29 +02:00
joshua 1c3045b43f Merge branch 'feat/sponsor-a-spot' 2026-10-19 15:04:40 +02:00
joshuaandClaude Opus 5.5 6a6f56f377 Bump to 1.20.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:04:37 +02:00
joshuaandClaude Opus 5.5 dff83d47af Add sponsor a spot
Events can allow sponsorships: a "Sponsor a spot" button lets anyone
(guests included) pay through Yoco for whole spots or a custom amount,
anonymously or with a name and message. Payments land as event
donations in a sponsorship pool that supervisors assign with the
existing donation flow. Adds optional public progress towards a goal,
a sponsor receipt and Automations thank-you, pool columns in the
Donations report, and sponsorship labels/filter in Payments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:04:29 +02:00
joshua 9bdd3250bf Merge branch 'feat/room-allocation' 2026-10-19 14:45:09 +02:00
joshuaandClaude Opus 5.5 4a2e6ba01b Bump to 1.19.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:45:06 +02:00
joshuaandClaude Opus 5.5 a6549bc032 Add rooms & groups allocation
Supervisors can split an event's named attendees into allocation sets
(rooms, small groups, buses) with capacity, gender and leader per group,
using a drag-and-drop board or auto-allocate (keep bookings together or
split them). Adds printable group and master lists (medical view
audited), the group on tickets and in My Events, messaging by group,
a "My groups" page for leaders, and an optional per-event gender
question for named attendees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:44:58 +02:00
joshua ab2260db1f Merge branch 'feat/ticket-transfer' 2026-10-19 14:23:34 +02:00
joshuaandClaude Opus 5.5 35f61a8ffb Bump to 1.18.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:23:31 +02:00
joshuaandClaude Opus 5.5 c40542dafd Add ticket transfer
Payers and holders can hand a ticket to someone else before the event.
The new holder gets a new QR code (and an inactive account with an
activation link if they're new); the old code stops working and scans
of it, online or in offline sync, say it was transferred. One place can
be split off a shared group ticket. Transfers can be turned off per
event (supervisors can always transfer from At the door), youth events
need the new holder's own consent, and every transfer is audited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:23:24 +02:00
joshua e280c7fab5 Merge branch 'feat/offline-scanning' 2026-10-19 14:06:40 +02:00
joshuaandClaude Opus 5.5 4e5faff617 Bump to 1.17.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:06:34 +02:00
joshuaandClaude Opus 5.5 ae7dbf457c Add offline ticket scanning
Staff can lock a section (or the whole event) to their device, download
its tickets and keep scanning with no connection. Scans are queued in
IndexedDB and synced idempotently when back online; conflicts go into a
sync report for supervisors, who can also force-release a lost device.
The server now validates scan sections and refuses scans in a scope
locked to another device. Adds a web app manifest and a service worker
for the scanner page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:06:22 +02:00
joshua c5b0032e1d Merge branch 'feat/waitlist' 2026-10-19 13:43:20 +02:00
joshuaandClaude Opus 5.5 50c6c61afb Bump to 1.16.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:43:16 +02:00
joshuaandClaude Opus 5.5 736d17caff Add waitlist for sold-out tickets
Events can take a waitlist for sold-out lines. When places free up
(cancellation, smaller booking, higher stock limit) the next person is
offered them with a claim link and the places are held for a set time;
unclaimed offers expire and move on, with optional partial offers. Stock
is now counted in one place (utils/stock.js), including held places,
and manual registrations and booking edits are now stock-checked. Adds a
supervisor waitlist page, My Events waitlists, and the daily summary count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:43:10 +02:00
joshua 123fb288b1 Merge branch 'feat/parental-consent' 2026-10-19 13:25:02 +02:00
joshuaandClaude Opus 5.5 a13b443ab7 Bump to 1.15.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:24:57 +02:00
joshuaandClaude Opus 5.5 f55353ecc6 Add parental consent for youth events
Youth events need a name and date of birth for every attendee, and a
parent/guardian's details for under-18s. Parents get an email and
WhatsApp link to a consent page that records the signed name, time, IP,
device and exact consent text; medical and emergency details are stored
encrypted. Tickets are issued but check-in is blocked until consent is
given (supervisor override audited). A daily job sends reminders and
purges medical details after the retention period. Adds a supervisor
consent tracker, consent status and medical list reports, and clears
consent data when an account is anonymised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:24:44 +02:00
joshua 03b79972e6 Merge branch 'feat/group-tickets' 2026-10-19 12:12:52 +02:00
joshuaandClaude Opus 5.5 1f42f35835 Bump to 1.14.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:12:44 +02:00
joshuaandClaude Opus 5.5 a357dea50f Add group tickets with named attendees
Events can take a name (and optional email/phone) for each main-ticket
place. Each named person gets their own quantity-1 ticket and attendee
form; unnamed places share one ticket. Tickets go to the payer or to each
person, attendees matching one existing account are linked to it, and
the payer can edit names and send form links from My Events. Ticket
generation is now planned per line (utils/attendees.js), free
registrations use the same generator, and guest registration matches
accounts by phone too, refusing conflicting email/phone pairs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:12:33 +02:00
joshua 66a0dc99bf Merge branch 'feat/coupon-codes' 2026-10-19 11:43:36 +02:00
joshuaandClaude Opus 5.5 0968fb02be Bump to 1.13.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:43:26 +02:00
joshuaandClaude Opus 5.5 efcac8b2c2 Add coupon codes and staff pricing
Percentage, fixed-amount and comp codes, limited by event, ticket option
or variant, dates, use counts, minimum quantity, and people, roles or an
email domain. The discount is locked in on the registration (mirrored on
Registration.discountTotal so every total sees it), shows on invoices,
receipts, emails and the Yoco checkout, and is released on cancellation.
Use limits are enforced under an advisory lock.

Ticket options and variants can also carry a staff price that Staff and
above get automatically. Adds a Supervisor > Coupon codes page, code
fields on registration, My Events, manual registration, at the door and
the kiosk, a Discounts report, and audit log entries. Also fixes Yoco
line items and the free-registration check for lines spanning several
price tranches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:43:10 +02:00
joshua 38b53f3195 Merge branch 'feat/required-2fa-staff-roles' 2026-10-19 11:00:51 +02:00
joshuaandClaude Opus 5.5 7dcb1a83e0 Bump to 1.12.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:00:47 +02:00
joshuaandClaude Opus 5.5 3f3a8cad66 Require two-factor authentication for admins and supervisors
Admins and supervisors without 2FA are sent a code at their next login,
and verifying it turns 2FA on. They can change the channel but not turn
it off. Older sessions without 2FA are rejected with TWO_FACTOR_REQUIRED,
and promoting a user ends their sessions so they enrol at next login.
The requirement is skipped when no email or WhatsApp channel can deliver
a code, and TWO_FACTOR_REQUIRED_ROLES=false switches it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:00:12 +02:00
joshuaandClaude Opus 5.5 12832dea67 Add FEATURES.md and refresh info.md
FEATURES.md is a repo-root overview of everything the platform does.
info.md, the overview for prospective churches, is brought up to date
with features added since it was written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:06:06 +02:00
joshuaandClaude Opus 5.5 ba79f25571 Bump to 1.11.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 14:49:34 +02:00
joshuaandClaude Opus 5.5 a21f12ae3c Add optional two-factor authentication
Users can turn on 2FA from Profile & Security and receive a 6-digit
login code by email or WhatsApp, with a "trust this device for 30 days"
option. Admins can reset it for a locked-out user, and the self-service
kiosk handles the code step at setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 14:49:34 +02:00
joshuaandClaude Opus 5.5 c06e12b7d9 Bump to 1.10.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:59:37 +02:00
joshuaandClaude Opus 5.5 05043379d9 Fix frontend build hanging when the backend is unreachable
Server-side fetches now fail fast when no API base URL is configured,
and the home and events pages build with an empty list if /api/events
can't be reached during next build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:59:30 +02:00
joshuaandClaude Opus 5.5 d6c99657a2 Update dependencies to clear npm audit advisories
Run npm audit fix in root, backend and frontend, bump nodemailer to 10,
override shell-quote in the root package, and allow-list the dependency
install scripts npm was blocking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:59:22 +02:00
joshuaandClaude Opus 5.5 abf7883490 Bump to 1.10.5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:46:36 +02:00
joshuaandClaude Opus 5.5 84ae0dbc55 Show in-progress events on home and events pages
Filter by endDate instead of startDate so events stay listed until they finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:46:04 +02:00
joshuaandClaude Sonnet 5 2cf4aa79a1 Bump to 1.10.4
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAwumFeBwx6XSsQXp8Nfqt
2026-09-01 09:04:31 +02:00
joshuaandClaude Sonnet 5 0c9676a466 Fix "Add to calendar" 400 when FRONTEND_URL lacks a scheme
The ics library's url validator requires a scheme (https://...), but
production's FRONTEND_URL/APP_BASE_URL was configured without one, so
createEvent() rejected every request before generating a .ics file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAwumFeBwx6XSsQXp8Nfqt
2026-09-01 09:00:17 +02:00
joshua 97c5c4cc6a Merge pull request 'Log event creation to admin audit log, add back button, bump to 1.10.3' (#3) from fix/event-create-audit-log-and-back-button into main 2026-08-28 14:49:24 +02:00
joshuaandClaude Sonnet 5 af39a25695 Also log staff cancellations via PUT /api/registrations/:id
Registrations can be cancelled two ways: DELETE /:id (owner or admin,
already logged registration_cancelled) and PUT /:id (staff+, status
change endpoint) — the latter was silently unlogged. Since PUT /:id
is staff-only, any transition into 'cancelled' there is inherently a
staff-initiated cancellation, so it's now logged the same way.

Audited all six categories promised in the 1.10.0 changelog entry
(refunds, donation assign/unassign, manual registrations,
staff-initiated cancellations, event create/update/delete, settings
changes) against their actual logAdminAction call sites and route
wiring — this was the only other gap found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 14:48:17 +02:00
joshuaandClaude Sonnet 5 08995d9882 Log event creation to admin audit log, add back button, bump to 1.10.3
createEvent never called logAdminAction, even though 1.10.0 already
listed event_created as a filterable action on the audit-log page —
only updateEvent/deleteEvent actually logged. Event creation is now
logged the same way, at every return path including the legacy
pre-migration retry branches.

Also adds a "Back to dashboard" link to Admin -> Audit log, matching
the existing back-link pattern on the Cashup page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 14:44:23 +02:00
joshua d892a0d153 Merge pull request 'Fix Sentry not instrumenting Express, bump version to 1.10.2' (#2) from fix/sentry-express-instrumentation-order into main 2026-08-28 13:22:54 +02:00
joshuaandClaude Sonnet 5 1a33f510f2 Fix Sentry not instrumenting Express, bump version to 1.10.2
express, cors, and @prisma/client were required at the top of
backend/src/index.js before Sentry.init() ran, so Sentry's
auto-instrumentation (which patches those modules via a require hook)
missed them — startup logged "[Sentry] express is not instrumented".
Sentry.init() now runs immediately after dotenv.config(), before any
of the libraries it instruments are required.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 13:21:19 +02:00
joshua 40880434f2 Merge pull request 'Fix upload path-traversal RCE vector, patch all known-vulnerable deps' (#1) from security/upload-path-traversal-and-dep-fixes into main 2026-08-28 12:44:21 +02:00
joshuaandClaude Sonnet 5 24679ed6ac Bump version to 1.10.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 12:36:55 +02:00
joshuaandClaude Sonnet 5 3e7ddcbe62 Fix upload path-traversal RCE vector, patch all known-vulnerable deps
Path traversal (CWE-22/CWE-73): event-image, branding (logo/favicon),
and event-attachment uploads built the saved filename from the
client-supplied original filename with no sanitization, and multer's
diskStorage joins that straight into the destination path. A crafted
filename containing `../` sequences could write the uploaded file
anywhere the server process has write access — reachable by any
supervisor-level account, and briefly pre-auth via the branding
uploads during initial /setup. Filenames are now always server-
generated (random bytes + validated extension); the original name is
kept only as display metadata.

Dependencies: express-rate-limit was declared only at the repo root
despite being required directly by backend/src/index.js, so a plain
`cd backend && npm install` (per the deployment doc) would never
install it — moved it into backend/package.json. Bumped next off a
version affected by a critical unauthenticated RCE (React Flight
protocol) and switched it from an exact pin to a caret range so future
patches install automatically. Bumped multer/nodemailer/jsonwebtoken/
uuid to patched versions, with an override forcing the vulnerable
nested uuid inside exceljs and the vulnerable postcss bundled inside
next to the patched versions too. `npm audit` is now clean (0
vulnerabilities) across root, backend, and frontend.

Hardening: jwt.verify() now pins algorithms: ['HS256'] instead of
trusting the token header; /uploads now serves with a restrictive CSP
and X-Content-Type-Options: nosniff so an uploaded SVG containing
<script> can't execute if opened directly.

Verified: backend's Jest suite passes, the backend boots and serves
real requests on the bumped deps, and `next build` compiles/type-
checks cleanly on the bumped frontend deps.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 11:33:05 +02:00
joshuaandClaude Sonnet 5 9aa1dd6a69 Bump version to 1.10.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 09:25:44 +02:00
joshuaandClaude Sonnet 5 d9dedd935a Ignore hope-events-deployment-setup.txt
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 09:22:24 +02:00
joshuaandClaude Sonnet 5 4a9ba8fec8 Add calendar export, SEO, error monitoring, backups, audit trail, and a starter test suite
Six site improvements picked from a "what could be better" review, plus a Jest
test suite covering the two areas with the trickiest money-handling history
in this project (early-bird pricing tranches, donation-leg accounting):

- "Add to calendar" .ics download on event pages and in confirmation emails
- sitemap.xml, robots.txt, and Open Graph/Twitter metadata for public pages
- Sentry error monitoring (backend + frontend), a no-op until SENTRY_DSN is set
- Nightly local pg_dump backups with a Site Settings tab to browse/trigger/download
- Admin audit trail for refunds, donations, manual registrations, event and
  settings changes, and staff-initiated cancellations
- Jest tests reproducing and guarding against the 1.8.0 tranche-pricing bug
  and the 1.4.2 donation-balance-inflation bug

Wallet passes (Google/Apple) were scoped out of this round — Apple Wallet
needs a paid Apple Developer account the project doesn't have yet, and the
user preferred shipping both together later rather than Google alone now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 14:50:11 +02:00
joshua 568a437069 Bump version to 1.9.5 2026-08-27 09:35:58 +02:00
joshua 47bc861487 Merge branch 'fix/alias-route-bot-traffic-oom' into main 2026-08-27 09:35:33 +02:00
joshuaandClaude Sonnet 5 5a83849549 Reject bot-probe paths on the event alias route before hitting the DB
The public [redirectUrl] catch-all route (and its backend counterpart,
GET /api/events/by-alias/:redirectUrl) matched any unmatched top-level
path, so routine bot/scanner traffic (/wp-login.php, /.env, etc.) was
firing a live database query on every hit. That traffic pattern looks
like the cause of the P1017 "server has closed the connection" storms
and OOM crashes seen from v1.7 onward. Both now reject anything that
isn't a plausible alias (letters/numbers/hyphens/underscores) before
touching Prisma.

Also adds a max_memory_restart safety net to PM2 for both processes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 09:33:23 +02:00
joshua 00db2261fb Run frontend PM2 process on port 3000 2026-08-26 14:38:29 +02:00
joshua aeda6f3b4d Add TRUST_PROXY env var for reverse-proxy deployments
Fixes express-rate-limit's ERR_ERL_UNEXPECTED_X_FORWARDED_FOR warning
and incorrect IP keying when nginx runs on a separate server in front
of the app.
2026-08-26 14:36:51 +02:00
joshua 1e50285e95 Add PM2 ecosystem config for production deployment 2026-08-26 11:59:08 +02:00
joshua 80e9595540 Merge branch 'fix/unhandled-rejection-no-crash' into main
Stops the server from hard-crashing on unhandled promise rejections, and bumps version to 1.9.3.
2026-08-26 09:07:06 +02:00
joshua 7a47b141f8 Bump version to 1.9.3 2026-08-26 09:06:52 +02:00
joshua c845c7cf0f Stop crashing the server on unhandled promise rejections
A single missed .catch() anywhere in the notification code (email/WhatsApp
sending) previously took down the whole process via process.exit(1). Log
the error instead and keep running.
2026-08-26 09:03:15 +02:00
joshuaandClaude Sonnet 5 cf549d440a Send activation link immediately for walk-in and manual registration accounts
Accounts created by staff on someone's behalf now get their activation
link (email or WhatsApp) sent right away, instead of only on a first
failed login attempt, matching what the Terms of Use already promised.
This also fixed a real account with a real email being silently
activated with a fixed, undisclosed password (Hope123).

Also fixes the self-service kiosk's "Create an account" password field,
which never actually took effect server-side, and removes the "Guest
(no account)" checkboxes that no longer had any backend effect once
every walk-in account started behaving the same way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 13:29:38 +02:00
joshuaandClaude Sonnet 5 91070e791b Bump version to 1.9.2
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:24:07 +02:00
joshua f15a035c9f Merge branch 'fix/contact-only-daily-summary' into main 2026-08-22 21:23:24 +02:00
joshuaandClaude Sonnet 5 b8c76c776f Skip daily summary emails for contact-only events
Contact-only events have no registration flow, so their daily
summary (registration/payment stats) was always empty — exclude
them from the query instead of sending a pointless email.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:22:53 +02:00
joshuaandClaude Sonnet 5 2d8db65622 Bump version to 1.9.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:12:37 +02:00
joshua 797440669f Merge branch 'fix/org-name-branding' into main 2026-08-22 21:11:52 +02:00
joshuaandClaude Sonnet 5 a95a7785eb Fix org name not showing in tab title, homepage, and backend pages
The browser tab title, homepage "Welcome to..." heading, and the
backend status/API docs pages all had the "Cross Code" default
hardcoded instead of reading the configured org_name setting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:09:35 +02:00
joshuaandClaude Sonnet 5 874c58762a Bump version to 1.9.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 11:51:27 +02:00
joshua 1b369fc5c3 Merge branch 'feature/event-location-maps' into main 2026-08-21 11:50:31 +02:00
joshua 72e9ffd42a Add event/organisation location with Google Maps links
Events and the organisation profile now have an address, with a
"Directions" link and an embedded Google Maps view (no API key
required) shown on event pages, event cards, and the Contact page.
New events default their location to the org's configured address.
2026-08-21 11:47:23 +02:00
joshua 56ed3c6da7 Merge branch 'feature/early-bird-tranches-and-contact-events' into main 2026-08-21 10:33:19 +02:00
joshuaandClaude Sonnet 5 3df92ffd00 Bump version to 1.8.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 10:32:17 +02:00
joshuaandClaude Sonnet 5 4b4c7a44a0 Add PDF invoices/receipts with manual send, fix early-bird tier edit data loss
- Registration confirmations attach an invoice PDF (itemized breakdown,
  early-bird discount, balance due, Yoco pay-now link/QR) whenever a
  balance is outstanding; payment/donation confirmations attach a
  payment receipt PDF. Sent as an email attachment and, over WhatsApp,
  as the PDF itself with the existing message as its caption.
- Users can also (re)send either document on demand: an "Invoice"
  button on the registration detail popup, and a "Receipt" button next
  to each payment there and on the Payment history page, each opening
  an Email/WhatsApp choice popup, via two new endpoints restricted to
  the registration/payment's own owner.
- Fix: editing an event option's early-bird tiers deleted and
  recreated every tier for that option with brand-new ids, silently
  severing the appliedTierId link on all historical purchases (losing
  early-bird attribution and undercounting stock-limit usage) even for
  tiers the admin didn't touch. Tiers are now upserted by id.
- Update the "My Events" help content and the API docs index for the
  new endpoints.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 10:26:49 +02:00
joshuaandClaude Sonnet 5 2cc6667378 Fix early-bird total in notifications; group dashboard registration items
Registration/payment/reminder emails and WhatsApp messages loaded
registrations without their price tranches, so any line spanning more
than one tranche fell back to charging the full quantity at the most
recent tranche's price, silently dropping the early-bird discount from
the outstanding balance and itemized amounts shown to the user.

The user dashboard's registration detail popup also listed one raw
line per tranche; it now merges same item/price/tier lines and groups
early-bird lines separately from standard-price ones.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 08:57:29 +02:00
joshuaandClaude Sonnet 5 90ed1d073f Fix early-bird price blending and mislabeling; add contact-only events
- Early-bird pricing: RegistrationOption now tracks each purchase as a
  separate price tranche instead of overwriting a single price/quantity
  on repeat purchases, so buying more tickets after a tier expires no
  longer re-prices tickets already bought at the old price. Stock-limit
  checks, total-due calculation, and the Finance report's revenue-by-
  option are all tranche-aware; pages that showed one blended price per
  line now render/total each tranche. Viewing a pending/partially-paid
  registration (dashboard, detail page, or an event's registration
  list) now refreshes stale pricing on the spot instead of only at
  payment time.
- Fixed the "(early bird)" dashboard label incorrectly firing on any
  line priced below the base option price (e.g. a plain cheaper
  variant) — it now checks the real applied-tier flag.
- Added contact-only events (e.g. baptism): no registration/payment
  flow, shown on the public site with a "Contact us" popup instead of
  a Register button. Configurable via the admin event wizard.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 17:26:35 +02:00
joshua cc17459117 Merge branch 'feature/site-branding-customization' into main 2026-08-20 14:57:44 +02:00
joshuaandClaude Sonnet 5 a6de39a08a Bump version to 1.7.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 14:57:23 +02:00
joshuaandClaude Sonnet 5 4d9e6a5107 Add admin-configurable branding (colors, logo, favicon) and generic default fallbacks
Site Settings -> Branding now supports a Primary/Secondary/Accent brand color
system applied site-wide (buttons, nav, hover states, links) and to outgoing
email header/CTA colors, plus a favicon upload alongside the existing logo
upload, a live preview panel (website/email x desktop/mobile), and
logo-based color suggestions. The setup wizard's Branding step got the same
treatment. Fixes two related bugs found along the way: the setup wizard's
logo/favicon upload was missing its auth token, and a static favicon.ico in
Next's special app/ convention path was silently overriding the dynamic one.

Also replaces every "Hope Events"/"Hope Family Church" default (org name,
email subjects, WhatsApp messages, report metadata, API docs) with a neutral
"Cross Code" placeholder, and the optional legal settings (operator name, IO
details, website URL, effective date) with obviously-generic placeholders
instead of defaulting to real personal/organisational details -- since this
platform is deployed for multiple organisations. Adds SETTINGS.md documenting
every setting's default behaviour.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 14:49:51 +02:00
joshua c465c96d95 Merge branch 'feature/supervisor-payments-improvements' into main 2026-08-08 01:24:52 +02:00
joshuaandClaude Sonnet 5 7ff9565f92 Bump version to 1.6.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 01:19:49 +02:00
joshuaandClaude Sonnet 5 12ba1f945f Add search and event filter to the Assigned donations list
Finding a specific leg to unassign meant scanning the whole list by
eye. Adds a text search (matches registrant, donor, or event) and an
event dropdown (built from events that actually have assigned legs)
above the list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 01:15:45 +02:00
joshuaandClaude Sonnet 5 43bf37aa5c Fix donation-assignment admin email reading as a real payment
The internal admin notice for applying a donation to a registration
reused buildPaymentAdminNotice as-is, so it read "Payment recorded" /
"Registration payment" — indistinguishable from an actual incoming
payment even though no new money changed hands. Adds a dedicated
buildDonationAssignmentAdminNotice wrapper (mirroring the one already
added for unassignment) so the subject, heading, and Type field all
say "Donation applied" instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 00:59:24 +02:00
joshuaandClaude Sonnet 5 393ca2551e Add ability to unassign a donation from a registration
Assigning a donation to a registration was one-way: the refund flow
could reverse the money but left the donation's "leg" payment in
place, permanently locking that portion of the donation as used even
though it had been refunded back out. Adds POST
/api/payments/unassign-donation, which deletes the leg, reverts the
registration's status/tickets the same way a refund downgrade already
does, and notifies the registrant. New "Assigned donations" list on
the supervisor Payments page surfaces existing legs with an Unassign
action, since no such list existed before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 00:53:21 +02:00
joshuaandClaude Sonnet 5 145f8a2801 Speed up payment/refund processing on the supervisor dashboard
Reconciling a Yoco payment and sending payment links blocked the HTTP
response on ticket-PDF generation and email/WhatsApp sends; they now
run in the background like the other payment flows already did.
Registration/payment option loops (pricing, stock checks, ticket
generation) now resolve concurrently instead of sequentially. The
Payments page dropped a per-registration N+1 fetch and now refreshes
its lists in parallel after each action. Added missing indexes for
dashboard stats and donation-leg lookups, and made GET
/api/registrations optionally paginated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 00:00:29 +02:00
joshua 705eba37d2 Merge branch 'fix/join-us-button-logged-in' into main 2026-08-07 01:57:23 +02:00
joshuaandClaude Sonnet 5 5d8896ecc2 Bump version to 1.5.4
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:57:02 +02:00
joshuaandClaude Sonnet 5 c80e8d3436 Fix Join Us button linking logged-in users to register page
Send logged-in users to their dashboard instead of the registration
form, matching how the Navbar already treats logged-in vs guest users.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:52:35 +02:00
joshua 2be398bdc0 Merge branch 'fix/help-modal-mobile-overflow' into main 2026-08-07 01:17:08 +02:00
joshuaandClaude Sonnet 5 9ee76af63e Bump version to 1.5.3
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:16:53 +02:00
joshuaandClaude Sonnet 5 5ac74859c6 Fix help guide popups overflowing the screen on mobile
The popup card had no overall height cap, only the tab content area
did, so the header/quick-links/footer could push the close button off
screen on short mobile viewports. The card is now capped to the
screen height with the header and footer pinned in place, and only
the tab content scrolls internally.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:14:44 +02:00
joshuaandClaude Sonnet 5 e3c837e8b3 Bump version to 1.5.2
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:47:54 +02:00
joshua d4d7b9df98 Merge branch 'fix/dashboard-mobile-styling' into main 2026-08-07 00:47:14 +02:00
joshua d8e2316f63 Add tab icons and fix mobile dashboard styling issues
- Add matching lucide-react icons to tab/mode switcher buttons on
  payments, at-the-door, manual, email-attendees, whatsapp-attendees,
  and admin cashup pages, mirroring icons already used in their help menus
- Fix navbar Logout button sitting lower than other nav links (missing
  border/padding classes that other links use for their active-underline)
- Fix stat card labels getting truncated on mobile by removing the
  ellipsis-cut label and widening the mobile grid to one column
- Fix Revenue trend / Top performing events rendering outside the
  viewport on mobile by containing horizontal overflow and truncating
  long event titles in the table
2026-08-07 00:41:52 +02:00
joshuaandClaude Sonnet 5 0ac5017204 Stop tracking banner.json runtime data store
Same reasoning as scheduled-emails.json: it's mutated by the running
app (site banner content), not source. readBanner() already falls
back to sane defaults when the file is missing, so untracking it is
safe for fresh checkouts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:04:45 +02:00
joshuaandClaude Sonnet 5 fccf220039 Stop tracking scheduled-emails.json runtime data store
It's mutated by the running app (scheduled job queue), not source -
committing it churns the repo with live recipient/message content.
Kept on disk, just untracked; a fresh checkout will get an empty
store created on demand by ensureStore().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:03:04 +02:00
joshua ef2c82ad7e Merge branch 'fix/whatsapp-scheduling-channel-bug' into main (1.5.1) 2026-08-07 00:01:01 +02:00
joshuaandClaude Sonnet 5 3ae9c9b964 Fix scheduled job list/edit dropping message content
toClient() never returned the message body (html/text for email,
message for WhatsApp), so "Manage scheduled" showed nothing to view
or edit even though the content existed in storage. Editing a
scheduled WhatsApp message also saved to the wrong payload field
(text instead of message), silently discarding the edit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:00:43 +02:00
joshuaandClaude Sonnet 5 87b3bff214 Bump version to 1.5.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 23:41:43 +02:00
joshua 520a1ae167 Merge branch 'fix/whatsapp-scheduling-channel-bug' 2026-08-06 23:40:32 +02:00
joshuaandClaude Sonnet 5 8e957d6401 Fix scheduled WhatsApp messages sending as email; add 24h cleanup and recipient display
The scheduled-job store never persisted the channel field, so the
send worker always fell through to its email branch regardless of
what was requested. Also purges sent jobs 24h after sending instead
of keeping them forever, and surfaces who each scheduled job will go
to in the admin "manage scheduled" lists (now correctly filtered per
channel too).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 23:37:35 +02:00
joshuaandClaude Sonnet 5 49ee8682d8 Bump version to 1.5.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:29:17 +02:00
joshuaandClaude Sonnet 5 49e28c15bf Merge branch 'feature/site-redesign' (1.5.0)
Full site visual redesign, site-wide contextual help system, dashboard
KPI overhaul (rolling trailing-month window), and assorted fixes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:27:39 +02:00
joshuaandClaude Sonnet 5 f08959e306 Help guide opens on demand only; add At the door to admin quick actions
- The site-wide help guide no longer auto-opens on first visit to a page
  — it only opens when the help button is clicked. Removed the
  now-pointless "Don't show this again" checkbox and the per-page
  dismissal tracking it drove.
- Admin dashboard quick actions was missing "At the door" (walk-in
  registration, payments, ticket printing), which Supervisor already had.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:17:12 +02:00
joshuaandClaude Sonnet 5 5c2e29ed1b Full site redesign, help system, and dashboard stats fixes
Multi-phase visual facelift (design tokens, dashboards, sidebar/navbar
shell, per-page help guides, and a layout/content pass across every
remaining page) plus backend fixes to the dashboard KPI stats:

- Admin/Supervisor dashboard KPIs (revenue, donations, registrations,
  tickets sold) now use a rolling trailing-month window (today back one
  calendar month, e.g. 9 May - 8 June if today is 8 June) instead of
  calendar month-to-date, which under-counted for most of the month.
  The comparison window shifts the same way, so like is still compared
  with like.
- Reports deep-links from those stat tiles now match the same window
  (range=trailing_month, replacing range=this_month).
- Design tokens (brand-* Tailwind scale + shadcn CSS variables), a
  site-wide contextual help button, fixed dashboard sidebar/navbar,
  Admin/Supervisor/Staff/User dashboard rebuilds backed by a new
  GET /api/stats/overview endpoint, a dedicated Contact page, Site
  Settings restyle with WhatsApp config folded in, and an Account
  activity feed backed by a new SecurityEvent model.
- Every remaining page (home, events, registration flow, auth, legal,
  payment results, and every Admin/Supervisor/Staff/User tool page)
  restyled onto the same design tokens, several with real layout
  upgrades (home hero, events list/detail, donate page, auth pages).
- 20+ new dedicated help guides so the whole site has page-specific
  help content instead of falling back to a generic guide.
- Assorted fixes surfaced along the way: donation-leg double-counting
  in payment stats, donations not counting toward revenue, refund
  netting in per-method report breakdowns, and donation
  over-allocation after a refund.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:00:10 +02:00
joshuaandClaude Sonnet 5 d715a45e22 Bump version to 1.4.2
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 09:13:04 +02:00
joshuaandClaude Sonnet 5 a6cec9d8bc Fix supervisor payments mobile tabs, reconcile donor, report method buckets, and refund/donation accounting
- Supervisor Payments: mode tabs now wrap on mobile instead of overflowing off-screen.
- Reconciling a Yoco transaction as a donation now lets staff pick who it's from.
- Reports payment-method breakdown now buckets into Cash/Card/EFT/Other everywhere,
  folding Apple Pay, Google Pay, and Yoco-portal payments into Card.
- Refunds now net against their original method's bucket (Cashup/Finance/Profit reports,
  My Payments filtering/display) instead of vanishing or falling into "Other".
- Refund form's method dropdown mirrors the real payment methods and auto-fills from the
  payment being refunded, replacing an ambiguous generic "Refund" option.
- Fixed donation remaining/unallocated balance inflating instead of shrinking when a
  donation is refunded (assign-donation endpoint, cashup reports, donations reports,
  and the Assign Donation panel all summed refund legs with the wrong sign).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 09:08:53 +02:00
joshuaandClaude Sonnet 5 bdb8993914 Bump version to 1.4.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 15:00:44 +02:00
joshuaandClaude Sonnet 5 8b3a0ced9f Fix Reports mobile layout overflow and desktop date range overflow
Report popup buttons and the page's search/Back controls overflowed
off-screen on mobile instead of wrapping, and the sidebar's custom
date range inputs spilled outside the filter box on desktop.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 14:57:09 +02:00
joshuaandClaude Sonnet 5 d858c7fcf5 Sync root package.json version to 1.4.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 15:49:03 +02:00
joshua c0f43c0e4c Merge branch 'feature/reports-and-cashup-overhaul' (1.4.0) 2026-08-04 15:46:55 +02:00
joshuaandClaude Sonnet 5 2434a7ffbd Bump version to 1.4.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 15:46:09 +02:00
joshuaandClaude Sonnet 5 144aee9d54 Hide dashboard sidebar on staff/supervisor/admin sub-pages; fix mobile overflow
- Sidebar now shows only on each role's root landing page
  (/dashboard/staff, /dashboard/supervisor, /dashboard/admin) and hides on
  every sub-page beneath them, not just Reports. Navbar's "Dashboard" link
  always leads back to the role root.
- Fixed two dropdown panels (EventsDropdown, the Email/WhatsApp Attendees
  recipient picker) that could extend past the viewport's right edge on
  narrow screens; both now stretch to their trigger's width like other
  dropdowns in the app already do.
- Wrapped the Admin Cashup event-costs table in the same overflow-auto
  container every sibling table on that page already uses, so it scrolls
  horizontally on narrow screens instead of squeezing its columns.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 15:30:56 +02:00
joshuaandClaude Sonnet 5 98f85e1465 Fix financial double-counting, rebuild cashup accountability, and redesign the Reports page
Financial correctness (donation-leg model):
- Donations are no longer mutated when assigned to a registration; assignment now
  creates an immutable "leg" record referencing the original donation instead.
- Fixed several places where money was double-counted once a donation was partially
  or fully assigned (Payments, Revenue summary, Cashup reconciliation, Finance
  report, Profit report, Master Orders, Revenue Detailed).
- Payments now record who recorded them (recordedBy), separate from who they're for.

Cashup:
- Per-user cash denomination counting (optional, any time) replaces the single
  event-wide manual entry; the event's cash actual is the live sum of these counts.
- New "Payment accountability by staff member" breakdown across all methods, and a
  read-only "Report" tab that opens automatically once an event is closed.

Reports page redesign:
- New shell: sidebar of universal filters (events, date range, past/inactive/closed
  toggles), searchable/categorized report grid, and a popup viewer with
  Print/Email/Excel/WhatsApp actions plus an in-app Reporting Guide.
- Visual pass: colored stat tiles and bar charts on most reports, matching mockups.
- PDF exports (download/Print/Email/WhatsApp) now share a branded design mirroring
  the web report — colored header, stat tiles, bar chart, highlighted totals.
- Excel export now produces a styled .xlsx (via exceljs) instead of a plain CSV.
- Master Orders' "Donations made" table is now included in every export channel.

Bug fixes discovered while testing exports:
- Report emails now go through the shared, DB-configurable mail utility instead of
  a one-off transporter that ignored Site Settings SMTP config.
- WhatsApp report sends now surface the actual WAWP API error and auto-recover a
  disconnected session, instead of a bare axios status-code message.

Also: Admin-editable notification preference, richer Admin Registrations dashboard,
{{payment.link}} placeholder for Email/WhatsApp Attendees, and background
email/WhatsApp attendee sending.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 14:52:54 +02:00
joshua f7ec9b1ca1 Merge branch 'fix/self-service-kiosk-lookup' 2026-08-03 13:03:12 +02:00
joshuaandClaude Sonnet 5 8e38e2faf6 Rework self-service kiosk account lookup for privacy and safety (1.3.2)
Replaces the explicit "look up existing account" search field with automatic
lookup as email/phone are entered, requires operator confirmation before any
matched account's name/email/phone/preference is changed, adds a password
show/hide toggle, and fixes two bugs found during testing: entering a phone
number belonging to a different account could silently overwrite the form
with that account's details, and re-checking an unchanged field (e.g. from
tapping a ticket quantity button) could revert edits already made. Also adds
a server-side check rejecting registrations whose email and phone resolve to
two different existing accounts, as defense in depth.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 12:56:26 +02:00
joshua ce80eb0829 Bump version to 1.3.1 2026-07-28 16:17:37 +02:00
joshua 6cf8c336d7 Merge branch 'fix/self-service-kiosk' 2026-07-28 16:16:31 +02:00
joshua aaa2108824 Populate email/phone from an unmatched kiosk search query
When the account lookup finds no match, carry the typed query into whichever
of Email/Phone it resembles (email-shaped or phone-shaped) instead of
discarding it, so the operator doesn't have to retype it. Leaves both blank
if it matches neither shape, and resets Name/notification preference for a
fresh entry.
2026-07-28 16:05:41 +02:00
joshua f57aea17bb Replace as-you-type account check with an explicit search field
The kiosk previously ran a debounced background lookup on every keystroke
in the visitor Email/Phone fields, silently autofilling matches. Replaced
with a dedicated "Look up existing account" field that only searches when
the operator presses Enter or clicks Search, and matches exactly against
either email or phone (never both from one query, to avoid digits in an
email being misread as an unrelated phone number). Also simplified the
"account already exists" banner wording.
2026-07-28 14:35:28 +02:00
joshua 6af60c739e Update changelog for self-service kiosk fixes 2026-07-28 14:24:21 +02:00
joshua d9fa08b383 Fix self-service kiosk: hide closed events and autofill known visitors
- GET /api/events/all gains an opt-in excludeClosed=true param, used only by
  the kiosk, so closed events no longer show as selectable there while other
  admin/supervisor screens that still need to see closed events are unaffected.
- GET /api/users/check-exists now also returns the matched account's name,
  email, phone, and notification preference (safe fields only). The kiosk's
  existing debounced lookup uses this to autofill whichever fields are still
  blank when a visitor enters an email or phone that matches an existing
  account, without overwriting anything already typed.
2026-07-28 14:21:47 +02:00
joshuaandClaude Sonnet 5 a916274a9d Bump version to 1.3.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:06:08 +02:00
joshuaandClaude Sonnet 5 1f82202776 Merge branch 'feature/door-checkin'
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:04:51 +02:00
joshuaandClaude Sonnet 5 734b344ddf Add door check-in flow for Main Tickets
Lets staff redeem a registration's Main Tickets by quantity at the door
(via the Payment/registration flow) instead of scanning each QR code,
and automatically emails/WhatsApps a check-in confirmation to the
attendee. Also routes the At The Door "Open" button and post-payment
flow dynamically: paid registrations jump straight to Check-In instead
of a forced ticket print, since tickets are already sent automatically.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 14:56:31 +02:00
joshuaandClaude Sonnet 5 803d605da4 Bump version to 1.2.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 10:35:21 +02:00
joshua d64c0a9fea Fix wrong auth token key and mislabeled loading dialog on payment flows
registration/success read the token from the wrong localStorage key
(token instead of hope_events_token), which broke registration/form
loading there and made the new "Pay with Yoco" checkout call fail with
"Not authorized, token failed" — switched to the shared auth context
like the rest of the app.

dashboard/user's "Make payment" reused the ticket-email dialog, which
hardcoded "Sending tickets…" while loading — the dialog now takes an
optional loading title/subtitle so payNow can show its own message.
2026-07-27 10:29:42 +02:00
joshua 8cc6e58875 Simplify self-service payments to full-amount checkout, add manual-page payment tab
Self-service "pay now" flows (registration success + user dashboard) now go
straight to a Yoco checkout for the full outstanding balance instead of
prompting for a partial amount; that page has been removed. Partial-amount
payment links remain supervisor/admin-only via the Payments dashboard.

Also adds a "Record Payment" tab to the supervisor manual registration page,
pre-filled with the most recently created registration, so staff can capture
a payment right after registering someone without leaving the page.
2026-07-27 10:14:49 +02:00
joshuaandClaude Sonnet 5 4f895b85b3 Bump version to 1.1.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 10:36:38 +02:00
joshuaandClaude Sonnet 5 f6dcf3a479 Add registration status badges and auto-dismissing dashboard messages
Two consistency fixes requested after the payment-method work:

1. Registration status (pending/confirmed/partial_paid/paid/cancelled)
   was printed as a raw string on the user dashboard. Added
   RegistrationStatusBadge mirroring the existing EventStatusBadge
   pattern, using the same status colors already established on
   dashboard/admin/registrations.

2. Inline success/error banners across dashboard pages persisted
   indefinitely. Added a shared useDismissingState hook (drop-in
   useState replacement that auto-clears a truthy value after 7s,
   resetting the timer on each update) and swapped it in across ~24
   dashboard files. Excluded: message-only modal dialogs (ticket-
   scanning's success/error confirmations) and two states that mix
   live form-validation feedback with async results inside actively-
   open forms (the registration-edit modal's editError, the event
   create/edit modal's error) - those keep persisting until the user
   acts, since auto-hiding a "fix this field" message mid-edit would
   be a regression. Also fixed at-the-door's existing bespoke
   auto-dismiss timers (10s/15s, one mislabeled as "5s") to the same
   consistent 7s, and removed admin/settings' manual x dismiss button
   in favor of the same auto-only behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 10:17:53 +02:00
joshuaandClaude Sonnet 5 fea9136382 Apply payment method normalization consistently across user-facing views
Audited every place Payment.method reaches the UI. The main user
dashboard's per-registration payment list (fed by GET
/api/payments/registration/:id) was still showing the raw gateway
string, since that endpoint is shared with the staff-facing supervisor
payments page and wasn't touched by the earlier /mypayments fix.

Extracted the cash/card/eft/voucher/other normalization (matching
normalizeUserMethod on the backend) into frontend/src/lib/paymentMethod.ts
and applied it to both user-facing payment displays. Staff-facing views
(supervisor payments, at-the-door, reports, cashup) intentionally keep
showing the raw method for reconciliation and were left unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:41:43 +02:00
joshuaandClaude Sonnet 5 bff568475c Fold apple_pay/google_pay into the card bucket, keep everything else under other
Per feedback: card-network wallet payments (Apple Pay, Google Pay) should
report and filter as "card" on the user payment history page rather than
"other", since they settle the same way as a card payment. Any other
gateway-reported method still falls under "other".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:27:52 +02:00
joshuaandClaude Sonnet 5 3a4ff57188 Switch payment method filter to a static list with an "other" bucket
Per feedback, drop the dynamic /mypayments/methods lookup (wasn't
loading reliably) in favor of a static cash/card/eft/voucher/other
dropdown. Server-side normalization now folds any gateway-reported
method outside those four manual-entry values (apple_pay, google_pay,
yoco, etc.) into "other" instead of "card", both in the returned data
and in the filter query.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:24:53 +02:00
joshuaandClaude Sonnet 5 6860db60c9 Normalize user-facing payment method to cash/card/eft/voucher
Per feedback, stop trying to surface every gateway-reported wallet
type (apple_pay, google_pay, yoco, ...) as its own filter/display
value on the user payment history page. Both /mypayments and
/mypayments/methods now fold anything outside the four manual-entry
methods into "card", both in the returned data and in the filter
query, so Apple Pay/Google Pay payments show up under Card.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:02:59 +02:00
joshuaandClaude Sonnet 5 2ef0cc1bb3 Populate payment method filter from real data instead of a guessed list
The previous fix hardcoded apple_pay/google_pay as extra filter options,
but Payment.method is free-text set by whatever the gateway reports, so
guessing at literal values was fragile and still didn't surface them for
this user. Add GET /api/payments/mypayments/methods returning the
distinct method values actually present in the user's payments, and have
the dashboard filter build its options from that instead. Also switch
the method filter from a startsWith match to an exact match, since the
values now come straight from the same column being filtered.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 08:55:58 +02:00
joshuaandClaude Sonnet 5 c89ed74fea Fix payment method handling for non-default types (apple_pay, google_pay)
Yoco webhook payments are tagged with whatever wallet type the gateway
reports, not just cash/card/eft/voucher. Cashup/report totals were
silently dropping those into the "other" bucket instead of "card", and
the new user payment history page couldn't filter by them and showed
raw snake_case values.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 08:28:59 +02:00
joshua 14465fee66 Add paginated payment history to user dashboard
Users can now view their own payments (excluding donations) with
server-side pagination (25/page), date range, method, and
payment/refund filters, both on the API and the new client page.
2026-07-23 18:02:53 +02:00
joshuaandClaude Sonnet 5 a6ac97309e Bump version to 1.0.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 17:08:28 +02:00
joshua 05666e2ab3 Merge branch 'bug/user-dash-closed-events-editable' 2026-07-23 17:07:05 +02:00
joshuaandClaude Sonnet 5 3632f67d8b Add closed/past/inactive status badges to user dashboard event titles
Adds an EventStatusBadge component shown next to every event title on
the dashboard (registrations list, upcoming events, tickets, and the
registration modal), with precedence Closed > Past > Inactive when
more than one applies — reusing the badge styling already established
in the supervisor events list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 16:56:32 +02:00
joshuaandClaude Sonnet 5 719e2df867 Block self-service payment and cancellation on closed/past registrations
Extends the earlier user-dashboard fix: canEditActive is renamed
canModifyActive and now also gates the "Make payment" and "Cancel
registration" actions, not just editing. Backend enforcement added to
cancelRegistration and createYocoCheckout to block past-event
self-service payment/cancellation server-side (cashup-closed events
were already blocked via assertEventOpen; admins/supervisors are
exempt from the past-date check, consistent with existing overrides).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 16:51:10 +02:00
joshuaandClaude Sonnet 5 9ed988d774 Fix user dashboard: buried edit errors, closed events not hidden, closed/past registrations editable
Registration-edit errors were set into a page-level error state rendered
behind the edit modal overlay; they now render inside the modal. The
"Show past events" toggle only hid date-based past events, letting
cashup-closed events leak through by default; a shared isEventOver()
check now covers both, applied to registrations, tickets, and the
Edit button visibility (mirroring the backend's own edit block).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 16:43:33 +02:00
joshua 7146f5cf77 Add CHANGELOG.md 2026-07-23 15:38:39 +02:00
joshua fc60671dd8 Normalize package versions to semver 1.0.0 2026-07-23 15:36:37 +02:00
joshua fdd2d241b4 Initial commit
Next.js + Express event management app for Hope Family Church.
2026-07-23 15:26:47 +02:00
951 changed files with 273427 additions and 207 deletions
+1
View File
@@ -25,3 +25,4 @@ npm-debug.log*
# OS
.DS_Store
Thumbs.db
temp/
+130 -1
View File
@@ -2,7 +2,136 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## Unreleased
## agent@1.1.1 - 2026-11-18
- **Stats keep going while a job runs.** The agent sent stats and polled in one loop, so during
a job (an install or update can take 30 minutes) the Hub heard nothing and alerted, by email,
that the server was down. Stats now go every minute on their own timer, job or not (Hub 2.3.1
also treats a server running a job as busy, for agents not updated yet).
- The agent reports its real version: 1.1.0 still said 1.0.1 (a test now keeps it equal to
package.json).
## accounts@1.0.0, contracts@1.5.0, agent@1.1.0 - 2026-11-18
Phase 3 (docs/ACCOUNTS-1.0-PLAN.md). Released before the VM test and a run on real Postgres (both still to do).
- **Accounts 1.0.0** (`apps/accounts`): the church's OpenID Connect provider, sign-in pages,
account page and admin. Details in `apps/accounts/CHANGELOG.md`.
- **Contracts 1.5.0:** `OIDC_CLIENT_PATHS` / `oidcClientAddresses`, `oidcClientSecret` (derived from
a link secret), `ACCOUNTS_CALL_PATH`, `OIDC_SCOPES`, `ACR_MFA`, `CHURCH_PATHS`,
`churchChangedSchema`, `churchObjectSchema`.
- **`packages/auth-client`** (new): the product side of signing in. **`packages/ui`**: first
components.
- **Scripts:** `products/accounts.sh`; `accounts` in `SUPPORTED_PRODUCTS`; `crosscode install
--products accounts` (one product per install) and `crosscode add <church> <product>`.
### Agent (1.1.0)
- Install jobs for Accounts, and `add-product` jobs (a product next to a church's others).
## events@2.4.0, contracts@1.4.0 - 2026-11-18
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
`packages/seo`. With Hub 2.2.0 (events-hub). Released before the e2e run on Postgres and the VM test; do both
before updating a church.
### Events (2.4.0)
- Protocol v2 with the site's own Ed25519 key, Settings → Linked products with Connect, the public
event feed (`/api/feed/v1/events`) and `event.changed`, and events from linked products on the
public pages. Details in `apps/events/CHANGELOG.md`.
### Contracts (1.4.0)
- `crosscode.link/1` (`link.connect`, `link.connected`, `link.disconnect`) with `signLink` /
`verifyLink`, PEM helpers, link secrets and nonces; `LINK_PATHS`, `FEED_PATHS`.
- The v2 heartbeat can carry `publicKey`; the reply's `publicKeyStatus` (`saved` / `matches` /
`mismatch`).
- `typesVersions` for `@crosscode/contracts/signing` (older `moduleResolution`).
### packages/seo (new)
- `eventJsonLd`, `churchJsonLd`, `canonicalUrl`, `pageMeta`, `jsonLdString` (ROADMAP-v3 §11).
### Scripts
- `crosscode` (Events): installs and builds the shared packages Events uses before it.
## events@2.3.1 - 2026-11-18
- Next.js 16.4.6 (security advisories for 16.2.0–16.4.4; Events wasn't exposed). Also brings
`apps/events/package.json` up to the release (it was left at 2.2.0). Details in
`apps/events/CHANGELOG.md`.
## agent@1.0.1 - 2026-11-18
- A `status` job on the central server is answered by the agent itself (its stats, frps and
the agent version). It used to run `crosscode status`, which central servers don't have, and
failed with `spawn /usr/local/bin/crosscode ENOENT`.
## events@2.3.0, contracts@1.3.0, agent@1.0.0 - 2026-11-17
Phase 1c (authenticator-app sign-in) and phase 1d (docs/AGENT-1.0-PLAN.md): installs, updates and
uninstalls from the Hub (Hub 2.1.0) through the agent. Tested end to end on a VM (church server +
central server + Hub, AGENT-1.0-PLAN §13 and EVENTS-2.2-PLAN §6).
### Events (2.3.0)
- Two-factor with an authenticator app, and recovery codes. The env template, the church export
and registering by itself from `HUB_LICENCE_KEY` for installs from the Hub. Details in
`apps/events/CHANGELOG.md`.
### Contracts (1.3.0)
- `crosscode.agent-job/1` (fixed job types, strict arguments), `crosscode.agent-report/1`,
`crosscode.script-report/1`, `crosscode.agent-stats/1`, the agent join / poll requests,
`crosscode.env-template/1` and `crosscode.church-export/1`.
- `@crosscode/contracts/signing`: Ed25519 jobs (over canonical JSON) and agent requests, config
sealed to a server (X25519 + HKDF + AES-256-GCM), export encryption.
### Agent (1.0.0)
- `apps/agent`: polls the Hub, checks every job (pinned key, server, time window, replays, type,
arguments) and runs the crosscode script for it; stats every minute; listens on nothing.
Install script, systemd unit, self-update with automatic revert.
### crosscode script
- `--json` reports and `--config` on every command; `.env` files from each release's env template
(appended to, never rewritten, on deploy); `install --frp` with Hub-given ports, a database on
another server, and clean-up on failure; frpc.ini blocks; `restart`, `export`, `uninstall`, `purge`.
- Fixed in the VM test: `adopt` applies a release's new migrations in the switch-over; a failed
migration is marked rolled back so later deploys aren't blocked; frpc is restarted once when its
admin lines are first added; a site's PM2 always runs under its own systemd unit (`pm2-<user>`),
so restarting or updating the agent never stops a site; tags are fetched with `--force`.
## events@2.2.0, contracts@1.2.0 - 2026-11-17
### Events
- **Cross Events 2.2.0**, the first release from this repo (`apps/events`, ROADMAP-v3 phase 1b):
moved in with its history, npm workspaces with one root lockfile, and the `crosscode` script
(`deploy`, `status`, `install`, `adopt`) in `scripts/`. Also AI use shown in tokens instead of
rand, and everything the backend serves under `/api`. Details in `apps/events/CHANGELOG.md`.
### Contracts
- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`,
`capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs.
### Docs
- The roadmap (`docs/ROADMAP-v3.md`) and the Hub protocol (`docs/hub-protocol.md`) move here from
`hope-events/docs/`, since they cover every product. New: `docs/HANDOVER.md` (where each phase
stands) and `docs/EVENTS-2.2-PLAN.md` (phase 1b, Cross Events into the monorepo).
## contracts@1.1.0 - 2026-11-04
### Contracts
- Hub protocol v2: optional `requires` on a release (`[{ product, version }]`), the sibling
versions it needs. The Hub refuses an update request with `409 REQUIREMENT_NOT_MET` until
they're met (Hub 2.0, ROADMAP-v3 §5). Optional, so the schema stays `/1`-compatible.
## contracts@1.0.0 - 2026-11-04
+14 -3
View File
@@ -1,7 +1,8 @@
# Cross Code platform
The monorepo for the Cross Code products that come after Cross Events, and the formats they share.
The plan is in `hope-events/docs/ROADMAP-v3.md` (decided 2026-11-03).
The plan for every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where
things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
| Folder | What | Status |
|--------|------|--------|
@@ -11,8 +12,18 @@ The plan is in `hope-events/docs/ROADMAP-v3.md` (decided 2026-11-03).
| `apps/website` | Church Website | Placeholder (phase 4) |
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
Cross Events (`joshua/hope-events`) and Cross Code Hub (`joshua/events-hub`) stay in their own
repos and install `@crosscode/contracts` from Gitea's package registry.
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
([`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md)). Cross Code Hub (`joshua/events-hub`) stays in
its own repo and gets `@crosscode/contracts` as a packed release committed there (decision 22).
## Docs
| File | What |
|------|------|
| [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) | The plan: products, contracts, Accounts, sync, Hub, servers, build order, pricing, decisions |
| [`docs/HANDOVER.md`](./docs/HANDOVER.md) | Where each phase stands and what's next |
| [`docs/hub-protocol.md`](./docs/hub-protocol.md) | Install ↔ Hub protocol, versions 1 and 2 (a copy lives in `events-hub`) |
| [`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md) | Phase 1b: Cross Events into the monorepo, the `crosscode` script |
## Rules (ROADMAP-v3 §1)
+27
View File
@@ -0,0 +1,27 @@
# Changelog — Accounts
## [1.0.0] - 2026-11-18
The first release (docs/ACCOUNTS-1.0-PLAN.md), with Hub 2.3.0 and agent 1.1.0. Released before the
VM test and a run on real Postgres; do both before installing it for a church.
### Added
- OpenID Connect provider (oidc-provider 9.13.3): authorization code with PKCE (S256) required,
ES256 keys made on first start, `crosscode.identity/1` claims in the ID token, no refresh tokens,
RP-initiated logout and OIDC Back-Channel Logout. Clients are the linked products (Connect,
`crosscode.link/1`), with exact redirect addresses and the client secret derived from the link.
- Sign-in steps that all return to the product and page they started from: password, sign-up with
an emailed code, two-step sign-in (authenticator app, email, WhatsApp, recovery codes) and setting
it up when a product asks (`acr_values=mfa`) or for admins, privacy notice (asked again when a new
version is published), news question, forgot / reset password.
- The account page: details, email change by link, password, two-step sign-in, recovery codes,
news consent, recent activity, sign out everywhere, download my data (bundled from every linked
product), delete my account (approved by an admin, then every product, retried when a product
says "not yet").
- Admin: people (access-logged), deletion requests, the church profile (`crosscode.church/1`,
served at `/api/church/v1`, `church.changed` to products), linked products, sign-in settings,
email and WhatsApp, privacy notice versions, licence, audit log. First-run `/setup`.
- Hub protocol v2 (product `accounts`, `CCA-` licence; never read-only), registering by itself from
`HUB_LICENCE_KEY`.
- `crosscode` hooks (`scripts/products/accounts.sh`), `env.template.json`, PM2 example.
+20 -1
View File
@@ -1,3 +1,22 @@
# Accounts
Placeholder: the per-church sign-in (OpenID Connect). Built in phase 3 of ROADMAP-v3 (see §3 there).
The church's sign-in for every Cross Code product (ROADMAP-v3 §3, phase 3; plan and decisions in
[docs/ACCOUNTS-1.0-PLAN.md](../../docs/ACCOUNTS-1.0-PLAN.md)). A small OpenID Connect provider per
church at `accounts.<address>`: people sign in once and are signed in to all the church's products,
coming back to the page they started on. Members never see it as a product; admins manage people,
sign-in settings, linked products and the church profile here.
- `backend/`: Express + oidc-provider 9 + Prisma (ES modules). `npm run dev`, `npm test` (Node's test
runner through tsx: the whole app against an in-memory database, with a test product on
openid-client), `npm run build`.
- `frontend/`: Next.js 16 pages (sign-in steps, account page, admin, setup), strict CSP with a nonce
per page, the church's colours from its profile.
- `e2e/`: Playwright on the real pages (`npx playwright test` in `apps/accounts`): the backend on an
in-memory database with a test product (`e2e/server.ts`), Next on 3210. No database needed.
- Roles stay in each product: Accounts only knows who someone is (plan §2, "Roles stay in each
product").
- Products sign in with `@crosscode/auth-client` (packages/auth-client).
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `ACCOUNTS_URL=http://localhost:3200`,
`LINKS_ALLOW_PRIVATE=true`), `npx prisma migrate deploy`, then `npm run dev` in both folders (the
frontend runs on 3200 with `next dev -p 3200` and sends /api to the backend on 5200).
+14
View File
@@ -0,0 +1,14 @@
# What's new in Accounts
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.0.0
- **One sign-in for all your church's sites and apps.** People sign in once with their own account
and are signed in to the church website, the app and Cross Events, and come back to the page they
were on.
- **Secure by default:** two-step sign-in with an authenticator app, email or WhatsApp, recovery
codes, and required for admins.
- **People control their own information:** they change their details, choose their news, download
their data or ask for their account to be deleted, all in one place.
+6
View File
@@ -0,0 +1,6 @@
node_modules/
dist/
src/generated/
.env
uploads/
exports/
+50
View File
@@ -0,0 +1,50 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.0.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
"main": "dist/index.js",
"scripts": {
"start": "node dist/index.js",
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
"postinstall": "prisma generate",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status"
},
"dependencies": {
"@crosscode/contracts": "*",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"express-rate-limit": "^8.6.2",
"nodemailer": "^10.3.0",
"oidc-provider": "9.13.3",
"pg-boss": "^11.1.2",
"zod": "^4.6.7"
},
"devDependencies": {
"@crosscode/auth-client": "*",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
"@types/nodemailer": "^6.4.17",
"@types/oidc-provider": "^9.13.1",
"@types/supertest": "^7.2.1",
"openid-client": "6.8.9",
"prisma": "^7.10.1",
"supertest": "^7.3.1",
"tsx": "^4.23.15",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=22"
}
}
+10
View File
@@ -0,0 +1,10 @@
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
import 'dotenv/config';
import { defineConfig } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: { path: 'prisma/migrations' },
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
datasource: { url: process.env.DATABASE_URL ?? '' },
});
@@ -0,0 +1,342 @@
-- Accounts 1.0.0: the first schema (docs/ACCOUNTS-1.0-PLAN.md §2).
-- CreateEnum
CREATE TYPE "AccountRole" AS ENUM ('member', 'admin');
-- CreateEnum
CREATE TYPE "AccountStatus" AS ENUM ('active', 'deactivated', 'deleted');
-- CreateEnum
CREATE TYPE "TwoFactorMethod" AS ENUM ('email', 'whatsapp', 'totp');
-- CreateTable
CREATE TABLE "Account" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"givenName" TEXT,
"familyName" TEXT,
"email" TEXT NOT NULL,
"emailVerified" BOOLEAN NOT NULL DEFAULT false,
"phone" TEXT,
"phoneVerified" BOOLEAN NOT NULL DEFAULT false,
"passwordHash" TEXT,
"role" "AccountRole" NOT NULL DEFAULT 'member',
"status" "AccountStatus" NOT NULL DEFAULT 'active',
"twoFactorMethod" "TwoFactorMethod",
"totpSecret" TEXT,
"totpLastStep" INTEGER,
"newsEmail" BOOLEAN NOT NULL DEFAULT false,
"newsWhatsApp" BOOLEAN NOT NULL DEFAULT false,
"newsAskedAt" TIMESTAMP(3),
"noticeVersionAccepted" INTEGER NOT NULL DEFAULT 0,
"failedSignIns" INTEGER NOT NULL DEFAULT 0,
"lockedUntil" TIMESTAMP(3),
"lastSignInAt" TIMESTAMP(3),
"deactivatedAt" TIMESTAMP(3),
"anonymisedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Account_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "RecoveryCode" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"codeHash" TEXT NOT NULL,
"usedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PendingSignIn" (
"uid" TEXT NOT NULL,
"accountId" TEXT,
"stage" TEXT NOT NULL,
"codeHash" TEXT,
"codeSentAt" TIMESTAMP(3),
"attempts" INTEGER NOT NULL DEFAULT 0,
"amr" TEXT[],
"pendingTotpSecret" TEXT,
"remember" BOOLEAN NOT NULL DEFAULT false,
"expiresAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "PendingSignIn_pkey" PRIMARY KEY ("uid")
);
-- CreateTable
CREATE TABLE "EmailToken" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"purpose" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"interactionUid" TEXT,
"expiresAt" TIMESTAMP(3) NOT NULL,
"usedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EmailToken_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "LoginEvent" (
"id" TEXT NOT NULL,
"accountId" TEXT,
"type" TEXT NOT NULL,
"clientId" TEXT,
"ip" TEXT,
"userAgent" TEXT,
"detail" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LoginEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PrivacyNotice" (
"version" INTEGER NOT NULL,
"title" TEXT NOT NULL,
"body" TEXT NOT NULL,
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"publishedById" TEXT,
CONSTRAINT "PrivacyNotice_pkey" PRIMARY KEY ("version")
);
-- CreateTable
CREATE TABLE "NoticeAcceptance" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"version" INTEGER NOT NULL,
"acceptedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "NoticeAcceptance_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ConsentChange" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"channel" TEXT NOT NULL,
"granted" BOOLEAN NOT NULL,
"source" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ConsentChange_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AccessLog" (
"id" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"targetId" TEXT NOT NULL,
"action" TEXT NOT NULL,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AccessLog_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AuditLog" (
"id" TEXT NOT NULL,
"actorId" TEXT,
"actorRole" TEXT NOT NULL,
"action" TEXT NOT NULL,
"targetType" TEXT NOT NULL,
"targetId" TEXT,
"metadata" JSONB,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AppSetting" (
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
);
-- CreateTable
CREATE TABLE "ProductLink" (
"installId" TEXT NOT NULL,
"product" TEXT NOT NULL,
"url" TEXT NOT NULL,
"publicKey" TEXT NOT NULL,
"secret" TEXT NOT NULL,
"connectedAt" TIMESTAMP(3) NOT NULL,
"connectedById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
);
-- CreateTable
CREATE TABLE "LinkNonce" (
"nonce" TEXT NOT NULL,
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
);
-- CreateTable
CREATE TABLE "OidcPayload" (
"id" TEXT NOT NULL,
"model" TEXT NOT NULL,
"payload" JSONB NOT NULL,
"grantId" TEXT,
"userCode" TEXT,
"uid" TEXT,
"accountId" TEXT,
"expiresAt" TIMESTAMP(3),
"consumedAt" TIMESTAMP(3),
CONSTRAINT "OidcPayload_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Delivery" (
"id" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"callId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"path" TEXT NOT NULL,
"body" JSONB NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"attempts" INTEGER NOT NULL DEFAULT 0,
"nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"lastError" TEXT,
"reply" JSONB,
"deliveredAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Delivery_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DataExport" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'collecting',
"parts" JSONB NOT NULL DEFAULT '{}',
"file" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"readyAt" TIMESTAMP(3),
"expiresAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "DataExport_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DeletionRequest" (
"id" TEXT NOT NULL,
"accountId" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'waiting_approval',
"requestedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"approvedAt" TIMESTAMP(3),
"approvedById" TEXT,
"products" JSONB NOT NULL DEFAULT '{}',
"completedAt" TIMESTAMP(3),
CONSTRAINT "DeletionRequest_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Account_email_key" ON "Account"("email");
-- CreateIndex
CREATE INDEX "Account_status_idx" ON "Account"("status");
-- CreateIndex
CREATE UNIQUE INDEX "RecoveryCode_codeHash_key" ON "RecoveryCode"("codeHash");
-- CreateIndex
CREATE INDEX "RecoveryCode_accountId_idx" ON "RecoveryCode"("accountId");
-- CreateIndex
CREATE INDEX "PendingSignIn_expiresAt_idx" ON "PendingSignIn"("expiresAt");
-- CreateIndex
CREATE UNIQUE INDEX "EmailToken_tokenHash_key" ON "EmailToken"("tokenHash");
-- CreateIndex
CREATE INDEX "EmailToken_accountId_purpose_idx" ON "EmailToken"("accountId", "purpose");
-- CreateIndex
CREATE INDEX "LoginEvent_accountId_createdAt_idx" ON "LoginEvent"("accountId", "createdAt");
-- CreateIndex
CREATE INDEX "NoticeAcceptance_accountId_idx" ON "NoticeAcceptance"("accountId");
-- CreateIndex
CREATE INDEX "ConsentChange_accountId_idx" ON "ConsentChange"("accountId");
-- CreateIndex
CREATE INDEX "AccessLog_targetId_createdAt_idx" ON "AccessLog"("targetId", "createdAt");
-- CreateIndex
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
-- CreateIndex
CREATE INDEX "LinkNonce_seenAt_idx" ON "LinkNonce"("seenAt");
-- CreateIndex
CREATE INDEX "OidcPayload_grantId_idx" ON "OidcPayload"("grantId");
-- CreateIndex
CREATE INDEX "OidcPayload_uid_idx" ON "OidcPayload"("uid");
-- CreateIndex
CREATE INDEX "OidcPayload_accountId_idx" ON "OidcPayload"("accountId");
-- CreateIndex
CREATE INDEX "OidcPayload_expiresAt_idx" ON "OidcPayload"("expiresAt");
-- CreateIndex
CREATE UNIQUE INDEX "Delivery_callId_key" ON "Delivery"("callId");
-- CreateIndex
CREATE INDEX "Delivery_status_nextAttemptAt_idx" ON "Delivery"("status", "nextAttemptAt");
-- CreateIndex
CREATE INDEX "Delivery_linkId_idx" ON "Delivery"("linkId");
-- CreateIndex
CREATE INDEX "DataExport_accountId_idx" ON "DataExport"("accountId");
-- CreateIndex
CREATE INDEX "DeletionRequest_status_idx" ON "DeletionRequest"("status");
-- AddForeignKey
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EmailToken" ADD CONSTRAINT "EmailToken_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "LoginEvent" ADD CONSTRAINT "LoginEvent_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "NoticeAcceptance" ADD CONSTRAINT "NoticeAcceptance_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ConsentChange" ADD CONSTRAINT "ConsentChange_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Delivery" ADD CONSTRAINT "Delivery_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DataExport" ADD CONSTRAINT "DataExport_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DeletionRequest" ADD CONSTRAINT "DeletionRequest_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
+287
View File
@@ -0,0 +1,287 @@
// Accounts 1.0.0 (docs/ACCOUNTS-1.0-PLAN.md). One database per church.
generator client {
provider = "prisma-client"
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
output = "../src/generated/prisma"
moduleFormat = "esm"
importFileExtension = "js"
}
datasource db {
provider = "postgresql"
}
enum AccountRole {
member
admin
}
enum AccountStatus {
active
deactivated
deleted
}
enum TwoFactorMethod {
email
whatsapp
totp
}
// A person. `id` is the OIDC `sub` every product keys its own records on.
model Account {
id String @id @default(uuid())
name String
givenName String?
familyName String?
email String @unique // lower-case
emailVerified Boolean @default(false)
phone String?
phoneVerified Boolean @default(false)
// Argon2id; bcrypt hashes imported from Cross Events verify too and are re-hashed at sign-in.
passwordHash String?
role AccountRole @default(member)
status AccountStatus @default(active)
twoFactorMethod TwoFactorMethod?
totpSecret String? // encrypted
totpLastStep Int?
newsEmail Boolean @default(false)
newsWhatsApp Boolean @default(false)
newsAskedAt DateTime?
noticeVersionAccepted Int @default(0)
failedSignIns Int @default(0)
lockedUntil DateTime?
lastSignInAt DateTime?
deactivatedAt DateTime?
anonymisedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
recoveryCodes RecoveryCode[]
tokens EmailToken[]
loginEvents LoginEvent[]
acceptances NoticeAcceptance[]
consentChanges ConsentChange[]
exports DataExport[]
deletionRequests DeletionRequest[]
@@index([status])
}
model RecoveryCode {
id String @id @default(uuid())
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
codeHash String @unique
usedAt DateTime?
createdAt DateTime @default(now())
@@index([accountId])
}
// One sign-in in progress (an oidc-provider interaction), through every step: password, 2FA,
// verifying a new email, the news question and the privacy notice. Keyed by the interaction uid.
model PendingSignIn {
uid String @id
accountId String?
stage String // password | two_factor | setup_two_factor | verify_email | notice | news | done
codeHash String?
codeSentAt DateTime?
attempts Int @default(0)
amr String[]
pendingTotpSecret String? // encrypted, while setting up an authenticator app during sign-in
remember Boolean @default(false)
expiresAt DateTime
createdAt DateTime @default(now())
@@index([expiresAt])
}
// Links sent by email: verify an address, reset a password. Only the hash is kept.
model EmailToken {
id String @id @default(uuid())
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
purpose String // verify_email | reset_password
tokenHash String @unique
// The sign-in the link belongs to, so it carries on to the product afterwards (§5).
interactionUid String?
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
@@index([accountId, purpose])
}
// Sign-ins and changes to how someone signs in (the person and admins see these).
model LoginEvent {
id String @id @default(uuid())
accountId String?
account Account? @relation(fields: [accountId], references: [id], onDelete: Cascade)
type String // sign_in | sign_in_failed | locked | password_reset | password_changed | two_factor_on | two_factor_off | recovery_code_used | recovery_codes_replaced | signed_out_everywhere
clientId String? // the product it was for
ip String?
userAgent String?
detail Json?
createdAt DateTime @default(now())
@@index([accountId, createdAt])
}
model PrivacyNotice {
version Int @id
title String
body String
publishedAt DateTime @default(now())
publishedById String?
}
model NoticeAcceptance {
id String @id @default(uuid())
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
version Int
acceptedAt DateTime @default(now())
@@index([accountId])
}
// Proof of news consent (POPIA): every change, with where it was given.
model ConsentChange {
id String @id @default(uuid())
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
channel String // email | whatsapp
granted Boolean
source String // sign_up | news_question | account_page | admin
createdAt DateTime @default(now())
@@index([accountId])
}
// Admins viewing or exporting a person.
model AccessLog {
id String @id @default(uuid())
actorId String
targetId String
action String // view | export
ip String?
createdAt DateTime @default(now())
@@index([targetId, createdAt])
}
model AuditLog {
id String @id @default(uuid())
actorId String?
actorRole String
action String
targetType String
targetId String?
metadata Json?
ip String?
createdAt DateTime @default(now())
@@index([createdAt])
}
model AppSetting {
key String @id
value String
updatedAt DateTime @updatedAt
}
// A linked product (Connect, crosscode.link/1). Each is also an OIDC client (§4): client_id is
// installId, the client secret is derived from `secret`, the addresses are fixed paths on `url`.
model ProductLink {
installId String @id
product String // events | website | app
url String
publicKey String
secret String // encrypted
connectedAt DateTime
connectedById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries Delivery[]
}
model LinkNonce {
nonce String @id
seenAt DateTime @default(now())
@@index([seenAt])
}
// oidc-provider's storage (sessions, grants, codes, interactions…), one row per model and id.
model OidcPayload {
id String @id // "<model>:<id>"
model String
payload Json
grantId String?
userCode String?
uid String?
// Sessions only: whose, so "sign out everywhere" can find them.
accountId String?
expiresAt DateTime?
consumedAt DateTime?
@@index([grantId])
@@index([uid])
@@index([accountId])
@@index([expiresAt])
}
// Back-channel calls to linked products (user.updated, user.deleted, user.export, church.changed),
// retried until they're answered.
model Delivery {
id String @id @default(uuid())
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
callId String @unique
type String
path String
body Json
status String @default("pending") // pending | delivered | failed
attempts Int @default(0)
nextAttemptAt DateTime @default(now())
lastError String?
reply Json?
deliveredAt DateTime?
createdAt DateTime @default(now())
@@index([status, nextAttemptAt])
@@index([linkId])
}
// "Download my data": Accounts' part plus each product's (user.export), bundled into one file.
model DataExport {
id String @id @default(uuid())
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
status String @default("collecting") // collecting | ready | expired
parts Json @default("{}")
file String?
createdAt DateTime @default(now())
readyAt DateTime?
expiresAt DateTime
@@index([accountId])
}
// "Delete my account": deactivated at once, then an admin approves, then every product answers.
model DeletionRequest {
id String @id @default(uuid())
accountId String
account Account @relation(fields: [accountId], references: [id], onDelete: Cascade)
status String @default("waiting_approval") // waiting_approval | approved | done | cancelled
requestedAt DateTime @default(now())
approvedAt DateTime?
approvedById String?
// { [installId]: { status: "pending" | "deleted" | "deferred", reason?, retryAfter? } }
products Json @default("{}")
completedAt DateTime?
@@index([status])
}
@@ -0,0 +1,42 @@
/**
* Accounts' part of a church's export when it leaves (`crosscode export` / uninstall, AGENT-1.0-PLAN
* §9): `accounts.json` in --out-dir, with the church profile and the people in plain terms (the
* same person fields as `crosscode.church-export/1`; no passwords, 2FA secrets or sign-in logs).
*
* npx tsx scripts/export-church.ts --out-dir <dir>
*/
import 'dotenv/config';
import fs from 'node:fs';
import path from 'node:path';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { loadConfig } from '../src/lib/config.js';
import { church } from '../src/church/profile.js';
const i = process.argv.indexOf('--out-dir');
const out = i > 0 ? process.argv[i + 1] : null;
if (!out) {
console.error('Usage: export-church.ts --out-dir <dir>');
process.exit(2);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const ctx = createCtx(loadConfig(), db);
const people = await db.account.findMany({ where: { status: { not: 'deleted' } }, orderBy: { name: 'asc' } });
const acceptances = await db.noticeAcceptance.findMany({ orderBy: { acceptedAt: 'asc' } });
const accepted = new Map(acceptances.map((a) => [a.accountId, a.acceptedAt]));
const data = {
product: 'accounts',
generatedAt: new Date().toISOString(),
church: await church(ctx),
people: people.map((p, n) => ({
ref: `p${n + 1}`, name: p.name, email: p.email, phone: p.phone, role: p.role === 'admin' ? 'accounts admin' : 'member',
createdAt: p.createdAt.toISOString(),
consent: { email: p.newsEmail, whatsapp: p.newsWhatsApp, privacyNoticeAcceptedAt: accepted.get(p.id)?.toISOString() ?? null },
})),
};
fs.mkdirSync(out, { recursive: true });
fs.writeFileSync(path.join(out, 'accounts.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
console.log(` accounts.json: ${data.people.length} people`);
await db.$disconnect();
@@ -0,0 +1,120 @@
/**
* People's accounts: what the products are told about someone (`crosscode.identity/1`), consent,
* lockout, and the codes sent for 2FA and verifying an address.
*/
import crypto from 'node:crypto';
import { IDENTITY_SCHEMA, type IdentityClaims, type Profile } from '@crosscode/contracts';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
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';
export const MAX_FAILED_SIGN_INS = 10;
export const LOCK_MINUTES = 15;
export const CODE_MINUTES = 10;
export const normaliseEmail = (e: unknown) => String(e ?? '').trim().toLowerCase();
export function emailProblem(email: string): string | null {
return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) && email.length <= 254 ? null : 'Enter a valid email address.';
}
/** +27821234567 from 0821234567 and the like; null when it can't be read. */
export function normalisePhone(raw: unknown): string | null {
const s = String(raw ?? '').trim();
if (!s) return null;
let d = s.replace(/\D/g, '');
if (s.startsWith('+')) return d.length >= 8 && d.length <= 15 ? `+${d}` : null;
if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`;
return d.length >= 8 && d.length <= 15 ? `+${d}` : null;
}
export function profileOf(a: Account): Profile {
return {
name: a.name,
given_name: a.givenName,
family_name: a.familyName,
email: a.email,
email_verified: a.emailVerified,
phone_number: a.phone,
phone_number_verified: a.phoneVerified,
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
};
}
/** The `crosscode.identity/1` claims (without `amr`, which comes from the sign-in itself). */
export async function identityClaims(ctx: Ctx, a: Account): Promise<Omit<IdentityClaims, 'amr'>> {
return {
schema: IDENTITY_SCHEMA,
sub: a.id,
...profileOf(a),
two_factor: a.twoFactorMethod,
privacy_notice_version: Math.max(1, a.noticeVersionAccepted || (await currentNoticeVersion(ctx))),
};
}
/** Tell every linked product the profile or consent changed (`user.updated`). */
export async function profileChanged(ctx: Ctx, accountId: string) {
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
if (!a || a.status !== 'active') return;
await queueCall(ctx, 'user.updated', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.updated', callId, occurredAt: ctx.now().toISOString(), sub: a.id, profile: profileOf(a) }));
}
/** Records news consent (POPIA proof of each change) and returns whether anything changed. */
export async function setNewsConsent(ctx: Ctx, a: Account, next: { email?: boolean; whatsapp?: boolean }, source: string): Promise<boolean> {
const changes: { channel: string; granted: boolean }[] = [];
if (next.email !== undefined && next.email !== a.newsEmail) changes.push({ channel: 'email', granted: next.email });
if (next.whatsapp !== undefined && next.whatsapp !== a.newsWhatsApp) changes.push({ channel: 'whatsapp', granted: next.whatsapp });
await ctx.db.account.update({
where: { id: a.id },
data: { ...(next.email !== undefined ? { newsEmail: next.email } : {}), ...(next.whatsapp !== undefined ? { newsWhatsApp: next.whatsapp } : {}), newsAskedAt: a.newsAskedAt ?? ctx.now() },
});
for (const c of changes) await ctx.db.consentChange.create({ data: { accountId: a.id, ...c, source, createdAt: ctx.now() } });
return changes.length > 0;
}
// ─── Lockout ──────────────────────────────────────────────────────────────────
export const isLocked = (ctx: Ctx, a: Account) => !!a.lockedUntil && a.lockedUntil > ctx.now();
export async function signInFailed(ctx: Ctx, a: Account, req?: Request) {
const failed = a.failedSignIns + 1;
const lock = failed >= MAX_FAILED_SIGN_INS;
await ctx.db.account.update({ where: { id: a.id }, data: { failedSignIns: lock ? 0 : failed, ...(lock ? { lockedUntil: new Date(ctx.now().getTime() + LOCK_MINUTES * 60e3) } : {}) } });
await loginEvent(ctx, a.id, lock ? 'locked' : 'sign_in_failed', req);
}
export async function signInSucceeded(ctx: Ctx, a: Account) {
await ctx.db.account.update({ where: { id: a.id }, data: { failedSignIns: 0, lockedUntil: null, lastSignInAt: ctx.now() } });
}
// ─── Codes by email or WhatsApp ───────────────────────────────────────────────
/** Where a code goes, partly hidden for the screen: "j***@hope.co.za", "+27 ** *** 4567". */
export function maskedTarget(a: Account, method: 'email' | 'whatsapp'): string {
if (method === 'whatsapp') return a.phone ? `${a.phone.slice(0, 3)} ** *** ${a.phone.slice(-4)}` : 'your phone';
const [user, domain] = a.email.split('@');
return `${user!.slice(0, 1)}***@${domain}`;
}
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 });
}
return { codeHash: hashToken(code), sentTo: maskedTarget(a, method) };
}
export const codeMatches = (code: unknown, hash: string | null | undefined) =>
!!hash && safeEqual(hashToken(String(code ?? '').replace(/\D/g, '')), hash);
export const newId = () => crypto.randomUUID();
@@ -0,0 +1,98 @@
/**
* Two-factor sign-in (as Cross Events 2.3): an authenticator app (TOTP), or a code by email or
* WhatsApp, with 10 single-use recovery codes. Used by the sign-in flow and the account page.
*/
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
import { codeMatches, sendCode, CODE_MINUTES } from './service.js';
import { loginEvent } from '../lib/audit.js';
import { hashRecoveryCode, newRecoveryCodes } from '../lib/recoveryCodes.js';
import { generateSecret, matchStep, otpauthUrl } from '../lib/totp.js';
export class TwoFactorError extends Error {
status = 400;
constructor(message: string, public code = 'BAD_CODE') {
super(message);
}
}
const METHODS = new Set(['totp', 'email', 'whatsapp']);
/** After a second factor: RFC 8176 `otp` and `mfa`. */
export const accessAfterTwoFactor = (amr: string[]) => [...new Set([...amr, 'otp', 'mfa'])];
export async function verifyTotp(ctx: Ctx, a: Account, code: unknown): Promise<boolean> {
if (!a.totpSecret) return false;
const step = matchStep(ctx.secrets.decrypt(a.totpSecret), code, { now: ctx.now().getTime(), afterStep: a.totpLastStep ?? -1 });
if (step === null) return false;
await ctx.db.account.update({ where: { id: a.id }, data: { totpLastStep: step } });
return true;
}
export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?: Request): Promise<boolean> {
const row = await ctx.db.recoveryCode.findUnique({ where: { codeHash: hashRecoveryCode(String(code)) } });
if (!row || row.accountId !== a.id || row.usedAt) return false;
await ctx.db.recoveryCode.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await loginEvent(ctx, a.id, 'recovery_code_used', req);
return true;
}
/** Starts setting up a method: an app gets a new secret to scan; email or WhatsApp gets a code. */
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) {
if (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
if (method === 'totp') {
const secret = generateSecret();
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
return {
encryptedSecret: ctx.secrets.encrypt(secret),
codeHash: null as string | null,
forScreen: { method: 'totp', secret, otpauthUrl: otpauthUrl(secret, a.email, issuer.shortName || issuer.name || 'Church') },
};
}
const sent = await sendCode(ctx, a, method as 'email' | 'whatsapp', 'setup');
return { encryptedSecret: null as string | null, codeHash: sent.codeHash, forScreen: { method, sentTo: sent.sentTo } };
}
/** Confirms the first code, turns the method on and returns new recovery codes (shown once). */
export async function confirmTwoFactorSetup(
ctx: Ctx, a: Account,
s: { method: unknown; code: unknown; pendingSecret: string | null; codeHash: string | null; codeSentAt: Date | null },
req?: Request,
): Promise<string[]> {
const method = String(s.method);
if (!METHODS.has(method)) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
let totpSecret: string | null = null;
let totpLastStep: number | null = null;
if (method === 'totp') {
if (!s.pendingSecret) throw new TwoFactorError('Start again: scan the QR code first.', 'RESTART');
const step = matchStep(ctx.secrets.decrypt(s.pendingSecret), s.code, { now: ctx.now().getTime() });
if (step === null) throw new TwoFactorError('That code isn\'t right. Check your authenticator app\'s time is correct.');
totpSecret = s.pendingSecret;
totpLastStep = step;
} else {
const fresh = s.codeSentAt && ctx.now().getTime() - s.codeSentAt.getTime() < CODE_MINUTES * 60e3;
if (!fresh || !codeMatches(s.code, s.codeHash)) throw new TwoFactorError('That code isn\'t right, or it has expired.');
}
await ctx.db.account.update({ where: { id: a.id }, data: { twoFactorMethod: method as 'totp' | 'email' | 'whatsapp', totpSecret, totpLastStep } });
const codes = await replaceRecoveryCodes(ctx, a.id);
await loginEvent(ctx, a.id, 'two_factor_on', req, { detail: { method } });
return codes;
}
export async function replaceRecoveryCodes(ctx: Ctx, accountId: string): Promise<string[]> {
const { codes, hashes } = newRecoveryCodes();
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
for (const codeHash of hashes) await ctx.db.recoveryCode.create({ data: { accountId, codeHash, createdAt: ctx.now() } });
return codes;
}
export async function turnOff(ctx: Ctx, accountId: string) {
await ctx.db.account.update({ where: { id: accountId }, data: { twoFactorMethod: null, totpSecret: null, totpLastStep: null } });
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
}
export async function recoveryCodesLeft(ctx: Ctx, accountId: string): Promise<number> {
return ctx.db.recoveryCode.count({ where: { accountId, usedAt: null } });
}
+260
View File
@@ -0,0 +1,260 @@
/**
* 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
* licence and the audit log. Admins only, signed in with 2FA; viewing a person is access-logged.
*/
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 { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
import { currentSession } from '../oidc/sessions.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
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 { licenceStatus } from '../hub/licence.js';
import { connect as connectHub } from '../hub/client.js';
import { productName } from '../oidc/clients.js';
const PAGE = 50;
export function adminRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
const admin = async (req: Request, res: Response) => {
const s = await currentSession(ctx, provider, req, res);
if (!s) throw new ApiError(401, 'UNAUTHENTICATED', 'Please sign in.');
if (s.account.role !== 'admin') throw new ApiError(403, 'FORBIDDEN', 'Only Accounts admins can do that.');
if ((await ctx.settings.bool('two_factor_required_for_admins', true)) && !s.amr.includes('mfa')) throw new ApiError(403, 'MFA_REQUIRED', 'Sign in again with your second step to use admin.');
return { id: s.account.id, role: 'admin' };
};
// ─── People ────────────────────────────────────────────────────────────────
r.get('/people', handle(async (req, res) => {
await admin(req, res);
const q = String(req.query.q ?? '').trim();
const page = Math.max(1, Number(req.query.page) || 1);
const where = {
status: { not: 'deleted' as const },
...(q ? { OR: [{ name: { contains: q, mode: 'insensitive' as const } }, { email: { contains: q.toLowerCase() } }] } : {}),
};
const [items, total] = await Promise.all([
ctx.db.account.findMany({ where, orderBy: { name: 'asc' }, skip: (page - 1) * PAGE, take: PAGE }),
ctx.db.account.count({ where }),
]);
return {
items: items.map((a) => ({ id: a.id, name: a.name, email: a.email, role: a.role, status: a.status, twoFactor: a.twoFactorMethod, lastSignInAt: a.lastSignInAt })),
total, page, pages: Math.max(1, Math.ceil(total / PAGE)),
};
}));
r.get('/people/:id', handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUnique({ where: { id: String(req.params.id) } });
if (!a || a.status === 'deleted') throw new ApiError(404, 'NOT_FOUND', 'That person wasn\'t found.');
await accessLog(ctx, me.id, a.id, 'view', req);
const [signIns, deletion, consents] = await Promise.all([
ctx.db.loginEvent.findMany({ where: { accountId: a.id }, orderBy: { createdAt: 'desc' }, take: 20 }),
ctx.db.deletionRequest.findFirst({ where: { accountId: a.id }, orderBy: { requestedAt: 'desc' } }),
ctx.db.consentChange.findMany({ where: { accountId: a.id }, orderBy: { createdAt: 'desc' }, take: 20 }),
]);
return {
id: a.id, name: a.name, email: a.email, emailVerified: a.emailVerified, phone: a.phone, role: a.role, status: a.status,
twoFactor: a.twoFactorMethod, recoveryCodesLeft: await recoveryCodesLeft(ctx, a.id), news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
noticeVersionAccepted: a.noticeVersionAccepted, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt, lockedUntil: a.lockedUntil,
signIns: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip })),
consents: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })),
deletion: deletion ? { id: deletion.id, status: deletion.status, requestedAt: deletion.requestedAt, products: deletion.products } : null,
};
}));
r.post('/people/:id/reset-two-factor', handle(async (req, res) => {
const me = await admin(req, res);
const id = String(req.params.id);
if (id === me.id) throw new ApiError(400, 'SELF', 'Change your own two-factor sign-in on your account page.');
await turnOff(ctx, id);
await signOutEverywhere(ctx, provider, id);
await loginEvent(ctx, id, 'two_factor_off', req, { detail: { by: 'admin' } });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'two_factor_reset', targetType: 'account', targetId: id, ip: clientIp(req) });
return { reset: true };
}));
r.post('/people/:id/unlock', handle(async (req, res) => {
const me = await admin(req, res);
await ctx.db.account.update({ where: { id: String(req.params.id) }, data: { lockedUntil: null, failedSignIns: 0 } });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'account_unlocked', targetType: 'account', targetId: String(req.params.id), ip: clientIp(req) });
return { unlocked: true };
}));
r.put('/people/:id/role', handle(async (req, res) => {
const me = await admin(req, res);
const role = req.body?.role === 'admin' ? 'admin' : 'member';
const id = String(req.params.id);
if (id === me.id && role !== 'admin') throw new ApiError(400, 'SELF', 'Ask another admin to change your role.');
await ctx.db.account.update({ where: { id }, data: { role } });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'role_changed', targetType: 'account', targetId: id, metadata: { role }, ip: clientIp(req) });
return { role };
}));
r.put('/people/:id/status', handle(async (req, res) => {
const me = await admin(req, res);
const id = String(req.params.id);
if (id === me.id) throw new ApiError(400, 'SELF', 'You can\'t deactivate your own account here.');
const active = req.body?.active === true;
await ctx.db.account.update({ where: { id }, data: active ? { status: 'active', deactivatedAt: null } : { status: 'deactivated', deactivatedAt: ctx.now() } });
if (!active) await signOutEverywhere(ctx, provider, id);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: active ? 'account_reactivated' : 'account_deactivated', targetType: 'account', targetId: id, ip: clientIp(req) });
return { active };
}));
// ─── Deletion requests ─────────────────────────────────────────────────────
r.get('/deletions', handle(async (req, res) => {
await admin(req, res);
const list = await ctx.db.deletionRequest.findMany({ where: { status: { in: ['waiting_approval', 'approved'] } }, orderBy: { requestedAt: 'asc' } });
const people = await ctx.db.account.findMany({ where: { id: { in: list.map((d) => d.accountId) } } });
const byId = new Map(people.map((p) => [p.id, p]));
return { items: list.map((d) => ({ id: d.id, status: d.status, requestedAt: d.requestedAt, approvedAt: d.approvedAt, products: d.products, person: { id: d.accountId, name: byId.get(d.accountId)?.name ?? '', email: byId.get(d.accountId)?.email ?? '' } })) };
}));
r.post('/deletions/:id/approve', handle(async (req, res) => {
const me = await admin(req, res);
if (!(await approveDeletion(ctx, String(req.params.id), me, req))) throw new ApiError(409, 'NOT_WAITING', 'That request isn\'t waiting for approval.');
return { approved: true };
}));
r.post('/deletions/:id/cancel', handle(async (req, res) => {
const me = await admin(req, res);
if (!(await cancelDeletion(ctx, String(req.params.id), me, req))) throw new ApiError(409, 'NOT_WAITING', 'That request isn\'t waiting for approval.');
return { cancelled: true };
}));
// ─── Privacy notice ────────────────────────────────────────────────────────
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 };
}));
r.post('/notices', handle(async (req, res) => {
const me = await admin(req, res);
const title = String(req.body?.title ?? '').trim();
const body = String(req.body?.body ?? '').trim();
if (!title || body.length < 50) throw new ApiError(400, 'VALIDATION', 'Give the notice a title and its full text.');
const n = await publish(ctx, { title, body }, me.id);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'notice_published', targetType: 'notice', targetId: String(n.version), ip: clientIp(req) });
return n;
}));
// ─── Church profile ────────────────────────────────────────────────────────
r.get('/church', handle(async (req, res) => {
await admin(req, res);
return church(ctx);
}));
r.put('/church', handle(async (req, res) => {
const me = await admin(req, res);
const c = await updateProfile(ctx, req.body ?? {});
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'church_profile_changed', targetType: 'setting', targetId: 'church_profile', ip: clientIp(req) });
return c;
}));
// ─── Settings (sign-in, email, WhatsApp) ────────────────────────────────────
r.get('/settings', handle(async (req, res) => {
await admin(req, res);
const out: Record<string, string | boolean | null> = {};
for (const key of ADMIN_SETTINGS) {
const v = await ctx.settings.get(key);
out[key] = SECRET_SETTINGS.has(key) ? !!v : v;
}
return out;
}));
r.put('/settings', handle(async (req, res) => {
const me = await admin(req, res);
const changed: string[] = [];
for (const [key, value] of Object.entries(req.body ?? {})) {
if (!ADMIN_SETTINGS.has(key)) continue;
// A secret left empty keeps what's there.
if (SECRET_SETTINGS.has(key) && (value === '' || value === true)) continue;
await ctx.settings.set(key, value === null || value === undefined ? null : String(value));
changed.push(key);
}
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
return { changed };
}));
r.post('/settings/test-email', limit(5), handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
return { sent: true };
}));
// ─── Linked products ───────────────────────────────────────────────────────
r.get('/linked-products', handle(async (req, res) => {
await admin(req, res);
const [listed, links] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany()]);
const ids = [...new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)])];
return {
hubConnected: !!(await ctx.settings.get('hub_install_id')),
items: ids.map((id) => {
const hubRow = listed.find((l) => l.installId === id);
const link = links.find((l) => l.installId === id);
const product = hubRow?.product ?? link!.product;
return { installId: id, product, name: productName(product), url: hubRow?.url ?? link!.url, listed: !!hubRow, connectedAt: link?.connectedAt ?? null, signsInHere: !!link };
}),
};
}));
r.post('/linked-products/:installId/connect', handle(async (req, res) => {
const me = await admin(req, res);
await connectTo(ctx, String(req.params.installId), me, req);
return { connected: true };
}));
r.post('/linked-products/:installId/disconnect', handle(async (req, res) => {
const me = await admin(req, res);
return disconnectFrom(ctx, String(req.params.installId), me, req);
}));
// ─── Licence, audit ────────────────────────────────────────────────────────
r.get('/licence', handle(async (req, res) => {
await admin(req, res);
const s = await licenceStatus(ctx);
return { connected: s.connected, state: s.state, customer: s.claims?.customer ?? null, endsAt: s.endsAt, daysLeft: s.daysLeft, lastHeartbeatAt: await ctx.settings.get('hub_last_heartbeat_at'), lastError: await ctx.settings.get('hub_last_error') };
}));
r.post('/licence', limit(5), handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
await connectHub(ctx, String(req.body?.licenceKey ?? ''), { name: a.name, email: a.email });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'hub_connected', targetType: 'setting', ip: clientIp(req) });
return { connected: true };
}));
r.get('/audit', handle(async (req, res) => {
await admin(req, res);
const items = await ctx.db.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 200 });
return { items };
}));
r.get('/deliveries', handle(async (req, res) => {
await admin(req, res);
const items = await ctx.db.delivery.findMany({ where: { status: { not: 'delivered' } }, orderBy: { createdAt: 'desc' }, take: 100 });
return { items: items.map((d) => ({ id: d.id, type: d.type, linkId: d.linkId, status: d.status, attempts: d.attempts, lastError: d.lastError, nextAttemptAt: d.nextAttemptAt })) };
}));
return r;
}
+68
View File
@@ -0,0 +1,68 @@
/**
* The Express app (docs/ACCOUNTS-1.0-PLAN.md §1). Everything is under /api, so the site and its API
* share one address (as Events 2.2): nginx sends /api to this backend and the rest to Next.js.
*
* /api/health version and database, for monitoring and the Hub
* /api/oidc/… the OpenID Connect provider (discovery, auth, token, …)
* /api/self/… the account page's own sign-in
* /api/church/v1, /api/links/v1/… for the church's other products
* /api/v2/… the pages' API (sign-in steps, account, admin, setup)
*/
import express from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from './context.js';
import { sameOrigin, sendError } from './http.js';
import { adminRouter } from './admin/routes.js';
import { interactionRouter, selfRouter } from './interaction/routes.js';
import { meRouter } from './me/routes.js';
import { LOGOUT_JS } from './oidc/pages.js';
import { publicRouter } from './public/routes.js';
import { setupRouter } from './setup/routes.js';
import { health } from './hub/client.js';
import { appVersion } from './lib/version.js';
export function createApp(ctx: Ctx, provider: Provider) {
const app = express();
app.disable('x-powered-by');
if (ctx.config.trustProxy) app.set('trust proxy', 1);
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'same-origin');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-Robots-Tag', 'noindex, nofollow');
next();
});
app.get('/api/health', async (_req, res) => {
const h = await health(ctx);
res.status(h.db ? 200 : 503).json({ status: h.db ? 'ok' : 'error', product: 'accounts', version: appVersion(), db: h.db });
});
app.get('/api/static/logout.js', (_req, res) => {
res.type('application/javascript').set('Cache-Control', 'public, max-age=3600').send(LOGOUT_JS);
});
// The provider parses its own bodies: mounted before express.json.
app.use('/api/oidc', provider.callback());
app.use('/api/self', selfRouter(ctx));
app.use('/api', publicRouter(ctx));
const v2 = express.Router();
v2.use(express.json({ limit: '64kb' }));
v2.use(sameOrigin(ctx));
v2.use(interactionRouter(ctx, provider));
v2.use(setupRouter(ctx));
v2.use(meRouter(ctx, provider));
v2.use('/admin', adminRouter(ctx, provider));
v2.use((_req, res) => res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } }));
app.use('/api/v2', v2);
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
if (res.headersSent) return next(err);
const e = err as { type?: string };
if (e?.type === 'entity.parse.failed') return res.status(400).json({ error: { code: 'VALIDATION', message: 'The body must be JSON.' } });
return sendError(res, err);
});
return app;
}
@@ -0,0 +1,97 @@
/**
* The church profile (`crosscode.church/1`), owned by Accounts (docs/ACCOUNTS-1.0-PLAN.md §7,
* decision 1). Admins edit it; it brands the sign-in pages; `GET /api/church/v1` serves it to the
* church's products; a change sends `church.changed` to each linked product.
*
* Stored as `church_profile` (the editable fields). `customerId` comes from the licence, `links`
* from the linked products, so neither can be typed in wrong.
*/
import { churchObjectSchema, churchSchema, CHURCH_SCHEMA, type Church } from '@crosscode/contracts';
import type { z } from 'zod';
import type { Ctx } from '../context.js';
import { customerId } from '../hub/licence.js';
import { queueCall } from '../links/deliveries.js';
/** Before the Hub has given a customer id (a site not connected yet). */
export const NO_CUSTOMER = '00000000-0000-4000-8000-000000000000';
/** The fields an admin edits: the contract minus what Accounts fills in itself. */
export const profileInputSchema = churchObjectSchema.omit({ schema: true, customerId: true, updatedAt: true, links: true }).partial({
shortName: true, campuses: true, serviceTimes: true, social: true,
});
export type ProfileInput = z.input<typeof profileInputSchema>;
type Stored = Partial<Omit<Church, 'schema' | 'customerId' | 'links'>> & { updatedAt?: string };
const DEFAULTS = (ctx: Ctx): Omit<Church, 'schema' | 'customerId' | 'links' | 'updatedAt'> => ({
name: 'Our church',
shortName: null,
timezone: ctx.config.timezone,
locale: 'en-ZA',
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } },
campuses: [],
serviceTimes: [],
contact: { email: null, phone: null, whatsapp: null, address: null },
social: [],
} as never);
export async function storedProfile(ctx: Ctx): Promise<Stored> {
return ctx.settings.json<Stored>('church_profile', {});
}
/** Whether `/setup` has given the church its name yet. */
export async function profileSet(ctx: Ctx): Promise<boolean> {
return !!(await storedProfile(ctx)).name;
}
export async function church(ctx: Ctx): Promise<Church> {
const stored = await storedProfile(ctx);
const links = await ctx.db.productLink.findMany();
const url = (product: string) => links.find((l) => l.product === product)?.url ?? null;
const merged = {
...DEFAULTS(ctx),
...stored,
schema: CHURCH_SCHEMA,
customerId: (await customerId(ctx)) ?? NO_CUSTOMER,
updatedAt: stored.updatedAt ?? new Date(0).toISOString(),
links: { website: url('website'), events: url('events'), app: url('app'), accounts: ctx.config.publicUrl },
};
const parsed = churchSchema.safeParse(merged);
// Never serve something the contract refuses: fall back to the name and defaults.
return parsed.success ? parsed.data : churchSchema.parse({ ...DEFAULTS(ctx), name: stored.name || 'Our church', schema: CHURCH_SCHEMA, customerId: merged.customerId, updatedAt: merged.updatedAt, links: merged.links });
}
export class ProfileError extends Error {
status = 400;
code = 'VALIDATION';
constructor(message: string, public fields: Record<string, string>) {
super(message);
}
}
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
const current = await storedProfile(ctx);
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
const check = profileInputSchema.safeParse(next);
if (!check.success) {
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
throw new ProfileError('Some details need fixing.', fields);
}
const updatedAt = ctx.now().toISOString();
await ctx.settings.set('church_profile', JSON.stringify({ ...check.data, updatedAt }));
await queueCall(ctx, 'church.changed', () => ({ schema: CHURCH_SCHEMA, type: 'church.changed', occurredAt: updatedAt, updatedAt }));
return church(ctx);
}
/** What the sign-in pages need to look like the church's own (public). */
export async function branding(ctx: Ctx) {
const c = await church(ctx);
return {
name: c.name,
shortName: c.shortName,
logoUrl: c.branding.logoUrl,
colours: c.branding.colours,
signupEnabled: await ctx.settings.bool('signup_enabled', true),
};
}
+29
View File
@@ -0,0 +1,29 @@
/**
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
* whole app against an in-memory database and messenger (tests/support/).
*/
import type { PrismaClient } from './generated/prisma/client.js';
import type { Config } from './lib/config.js';
import { Secrets } from './lib/crypto.js';
import { LiveMessenger, type Messenger } from './lib/messages.js';
import { Settings } from './lib/settings.js';
export type Db = PrismaClient;
export type Ctx = {
config: Config;
db: Db;
secrets: Secrets;
settings: Settings;
messenger: Messenger;
now: () => Date;
};
export function createCtx(config: Config, db: Db, opts: { messenger?: Messenger; now?: () => Date } = {}): Ctx {
const secrets = new Secrets(config.secret);
const partial = { config, db, secrets } as Ctx;
partial.settings = new Settings(partial);
partial.messenger = opts.messenger ?? new LiveMessenger(partial);
partial.now = opts.now ?? (() => new Date());
return partial;
}
+53
View File
@@ -0,0 +1,53 @@
/**
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Events' /api/v2),
* async handlers, a same-origin check on everything that changes something, and rate limits.
*/
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import rateLimit from 'express-rate-limit';
import type { Ctx } from './context.js';
export class ApiError extends Error {
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
super(message);
}
}
type Fielded = { status?: number; code?: string; fields?: Record<string, string>; message: string };
/** Known errors from the services carry a status and code; anything else is a 500. */
export function sendError(res: Response, e: unknown) {
const err = e as Fielded;
if (e instanceof ApiError || (typeof err?.status === 'number' && typeof err?.code === 'string')) {
return res.status(err.status!).json({ error: { code: err.code, message: err.message, ...(err.fields ? { fields: err.fields } : {}) } });
}
console.error('[api]', e);
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
}
export const handle = (fn: (req: Request, res: Response) => Promise<unknown>): RequestHandler => (req, res) => {
fn(req, res).then((out) => {
if (out !== undefined && !res.headersSent) res.json(out);
}).catch((e) => sendError(res, e));
};
/**
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address. With
* SameSite=Lax cookies this stops another site posting on someone's behalf.
*/
export function sameOrigin(ctx: Ctx): RequestHandler {
const own = new URL(ctx.config.publicUrl).origin;
return (req: Request, res: Response, next: NextFunction) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
const origin = req.get('origin') || (req.get('referer') ? new URL(req.get('referer')!).origin : null);
if (origin === own || (!ctx.config.production && origin && /^https?:\/\/localhost(:\d+)?$/.test(origin))) return next();
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
};
}
export const limit = (max: number, minutes = 15): RequestHandler => rateLimit({
windowMs: minutes * 60e3,
limit: max,
standardHeaders: true,
legacyHeaders: false,
handler: (_req, res) => res.status(429).json({ error: { code: 'RATE_LIMITED', message: 'Too many tries. Please wait a few minutes.' } }),
});
+172
View File
@@ -0,0 +1,172 @@
/**
* Accounts and the Hub (docs/hub-protocol.md §6, protocol v2 from the start, product `accounts`):
* register with a `CCA-` licence key (from `/setup`, or by itself from HUB_LICENCE_KEY on a Hub
* install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's
* `linkedProducts` (the church's other installs) is cached for Connect.
*/
import crypto from 'node:crypto';
import { hub } from '@crosscode/contracts';
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';
export const PROTOCOL_VERSION = 2;
const TIMEOUT_MS = 15000;
const DAY = 24 * 60 * 60 * 1000;
const STARTED_AT = Date.now();
export class HubError extends Error {
constructor(message: string, public code: string, public status: number) {
super(message);
}
}
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
const raw = JSON.stringify(body);
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (sign) {
const timestamp = ctx.now().toISOString();
headers['X-Hub-Install'] = sign.installId;
headers['X-Hub-Timestamp'] = timestamp;
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
}
let res: Response;
try {
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (e) {
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
}
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
return data;
}
const version = appVersion;
export async function health(ctx: Ctx) {
let db = true;
try {
await ctx.db.$queryRawUnsafe('SELECT 1');
} catch {
db = false;
}
return {
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
db,
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
lastBackupAt: null,
disk: null,
errorsLast24h: null,
pendingMigrations: 0,
};
}
/** Aggregate counts only (hub.accountsStatsSchema): never anyone's details. */
export async function stats(ctx: Ctx) {
const since = new Date(ctx.now().getTime() - 90 * DAY);
const active = { status: 'active' as const };
const [total, active90d, email, whatsapp, totp, off, links] = await Promise.all([
ctx.db.account.count({ where: active }),
ctx.db.account.count({ where: { ...active, lastSignInAt: { gte: since } } }),
ctx.db.account.count({ where: { ...active, twoFactorMethod: 'email' } }),
ctx.db.account.count({ where: { ...active, twoFactorMethod: 'whatsapp' } }),
ctx.db.account.count({ where: { ...active, twoFactorMethod: 'totp' } }),
ctx.db.account.count({ where: { ...active, twoFactorMethod: null } }),
ctx.db.productLink.count(),
]);
return { accounts: { total, active90d }, twoFactor: { email, whatsapp, totp, off }, linkedProducts: links };
}
/** Register with a licence key (from /setup or HUB_LICENCE_KEY). */
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('ACCOUNTS_URL isn\'t set.', 'NO_SITE_URL', 400);
const { publicKeyPem } = await keyPair(ctx);
const profile = await ctx.settings.json<{ name?: string }>('church_profile', {});
const body = {
protocolVersion: PROTOCOL_VERSION,
licenceKey: licenceKey.trim().toUpperCase(),
product: 'accounts',
install: {
name: profile.name || 'Accounts',
url: ctx.config.publicUrl,
adminContact,
version: version(),
timezone: ctx.config.timezone,
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
features: { whatsapp: await ctx.messenger.whatsappReady() },
publicKey: publicKeyPem,
},
};
const check = hub.registerRequestSchema.safeParse(body);
if (!check.success) throw new HubError(`That doesn't look like an Accounts licence key (CCA-…).`, 'INVALID_REQUEST', 400);
const data = await post(ctx, '/api/installs/register', check.data);
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
await ctx.settings.setMany({
hub_install_id: String(data.installId),
hub_install_secret: String(data.installSecret),
hub_licence: String(data.licence),
hub_last_heartbeat_at: ctx.now().toISOString(),
hub_last_error: null,
hub_public_key_status: 'matches',
});
await saveLinkedProducts(ctx, data.linkedProducts);
return claims;
}
/** The `hub-heartbeat` job. Skips quietly when not connected. */
export async function heartbeat(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
const secret = await ctx.settings.get('hub_install_secret');
if (!installId || !secret) return { skipped: 'not connected' };
const status = await ctx.settings.get('hub_public_key_status');
const { publicKeyPem } = await keyPair(ctx);
const body = {
protocolVersion: PROTOCOL_VERSION,
product: 'accounts',
version: version(),
health: await health(ctx),
stats: await stats(ctx),
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
};
try {
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
await ctx.settings.setMany({
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
hub_last_heartbeat_at: ctx.now().toISOString(),
hub_last_error: null,
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
});
await saveLinkedProducts(ctx, data.linkedProducts);
return { ok: true };
} catch (e) {
const err = e as HubError;
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
if (err.code === 'INSTALL_NOT_FOUND') {
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
return { ok: false, reconnect: true };
}
throw e;
}
}
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY (as Events 2.3). Never throws. */
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
const key = ctx.config.hubLicenceKey;
if (!key) return { connected: false, reason: 'no_key' };
for (let i = 1; i <= attempts; i++) {
try {
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
return { connected: true };
} catch (e) {
const err = e as HubError;
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
}
}
return { connected: false, reason: 'unreachable' };
}
+69
View File
@@ -0,0 +1,69 @@
/**
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
* key, as Cross Events does. **Accounts never goes read-only** (docs/ACCOUNTS-1.0-PLAN.md §9,
* decision 4): a lapsed licence only shows admins a banner, so members can always sign in.
*/
import crypto from 'node:crypto';
import type { Ctx } from '../context.js';
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
const DAY = 24 * 60 * 60 * 1000;
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
export function normalisePem(input: string | null | undefined): string | null {
const text = String(input || '').replace(/\\n/g, '\n').trim();
if (!text) return null;
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
}
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
}
export type LicenceClaims = {
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
};
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
if (!pem) return null;
const parts = String(token || '').split('.');
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
try {
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
} catch {
return null;
}
}
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
/** The state for verified claims. Pure. */
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
return { state: 'lapsed', endsAt, daysLeft: null };
}
export async function licenceStatus(ctx: Ctx) {
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
const claims = verifyToken(token, hubPublicKey(ctx));
const valid = claims && claims.installId === installId ? claims : null;
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
}
/** The church's Hub customer id (the same for every product), once the licence says it. */
export async function customerId(ctx: Ctx): Promise<string | null> {
return (await licenceStatus(ctx)).claims?.customerId ?? null;
}
+43
View File
@@ -0,0 +1,43 @@
/**
* Starts Accounts: database, OIDC provider, HTTP server, jobs, and (on a Hub install) registering
* with the Hub from HUB_LICENCE_KEY.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from './generated/prisma/client.js';
import { createApp } from './app.js';
import { createCtx } from './context.js';
import { connectFromEnv, heartbeat } from './hub/client.js';
import { startJobs } from './jobs.js';
import { loadConfig } from './lib/config.js';
import { createProvider } from './oidc/provider.js';
async function main() {
const config = loadConfig();
const url = process.env.DATABASE_URL;
if (!url) throw new Error('DATABASE_URL isn\'t set.');
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
const ctx = createCtx(config, db);
const provider = await createProvider(ctx);
const app = createApp(ctx, provider);
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
const stopJobs = await startJobs(ctx, url);
connectFromEnv(ctx).then((r) => {
if (r.connected) heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
server.close();
await stopJobs();
await db.$disconnect();
process.exit(0);
};
process.on('SIGTERM', stop);
process.on('SIGINT', stop);
}
main().catch((e) => {
console.error('[accounts] Failed to start:', e);
process.exit(1);
});
@@ -0,0 +1,246 @@
/**
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). oidc-provider hands us an interaction
* (`uid`); `PendingSignIn` keeps where the person is in it, so every step — password, 2FA, setting
* up 2FA, verifying a new email, the privacy notice, the news question, and a password reset in
* between — carries on to the product they came from.
*
* password ─┬─ verify_email ─ two_factor | setup_two_factor ─ notice ─ news ─ done
* sign-up ──┘
*
* A session that's already signed in skips the password (the provider asked again only because a
* product wants 2FA, or the notice changed).
*/
import { ACR_MFA } from '@crosscode/contracts';
import type { Request } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import type { Account, PendingSignIn } from '../generated/prisma/client.js';
import {
codeMatches, emailProblem, isLocked, maskedTarget, normaliseEmail, normalisePhone, sendCode, setNewsConsent, signInFailed, signInSucceeded, CODE_MINUTES,
} from '../accounts/service.js';
import { accessAfterTwoFactor, confirmTwoFactorSetup, startTwoFactorSetup, useRecoveryCode, verifyTotp } from '../accounts/twoFactor.js';
import { loginEvent } from '../lib/audit.js';
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
import { productName } from '../oidc/clients.js';
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
export class FlowError extends Error {
constructor(message: string, public code = 'INVALID', public status = 400, public fields?: Record<string, string>) {
super(message);
}
}
type Details = Awaited<ReturnType<Provider['interactionDetails']>>;
const PENDING_MINUTES = 60;
export function mfaRequested(details: Details): boolean {
return String(details.params.acr_values ?? '').split(' ').includes(ACR_MFA);
}
/** Where someone goes next, from what's done so far. */
export async function nextStage(ctx: Ctx, pending: PendingSignIn, details: Details): Promise<Stage> {
if (!pending.accountId) return 'password';
const a = await ctx.db.account.findUnique({ where: { id: pending.accountId } });
if (!a || a.status !== 'active') return 'password';
if (!a.emailVerified) return 'verify_email';
const adminNeeds2fa = a.role === 'admin' && (await ctx.settings.bool('two_factor_required_for_admins', true));
const wants2fa = !!a.twoFactorMethod || mfaRequested(details) || adminNeeds2fa;
if (wants2fa && !pending.amr.includes('mfa')) return a.twoFactorMethod ? 'two_factor' : 'setup_two_factor';
if (a.noticeVersionAccepted < (await currentNotice(ctx)).version) return 'notice';
if (!a.newsAskedAt) return 'news';
return 'done';
}
/** The interaction's pending sign-in, made on first sight (signed in already: the session's account and how it signed in). */
export async function pendingFor(ctx: Ctx, details: Details): Promise<PendingSignIn> {
const existing = await ctx.db.pendingSignIn.findUnique({ where: { uid: details.uid } });
if (existing && existing.expiresAt > ctx.now()) return existing;
const reasons = (details.prompt?.reasons ?? []) as string[];
// Only skip the password when the provider asked again for one of our own reasons.
const trustSession = !!details.session?.accountId && reasons.every((r) => r === 'mfa_required' || r === 'account_needs_attention');
const data = {
uid: details.uid,
accountId: trustSession ? details.session!.accountId : null,
stage: 'password',
amr: trustSession ? ((details.session as { amr?: string[] }).amr ?? ['pwd']) : [],
attempts: 0,
expiresAt: new Date(ctx.now().getTime() + PENDING_MINUTES * 60e3),
};
return ctx.db.pendingSignIn.upsert({ where: { uid: details.uid }, create: data, update: data });
}
async function save(ctx: Ctx, pending: PendingSignIn, data: Partial<PendingSignIn>): Promise<PendingSignIn> {
return ctx.db.pendingSignIn.update({ where: { uid: pending.uid }, data: data as never });
}
async function account(ctx: Ctx, pending: PendingSignIn): Promise<Account> {
const a = pending.accountId ? await ctx.db.account.findUnique({ where: { id: pending.accountId } }) : null;
if (!a || a.status !== 'active') throw new FlowError('Please sign in again.', 'RESTART', 409);
return a;
}
/** What the page for the current step needs. Sends the code when a step needs one and none was sent. */
export async function describe(ctx: Ctx, details: Details, pending: PendingSignIn) {
const stage = await nextStage(ctx, pending, details);
if (stage !== pending.stage) pending = await save(ctx, pending, { stage, codeHash: null, codeSentAt: null, attempts: 0 });
const client = details.params.client_id ? await ctx.db.productLink.findUnique({ where: { installId: String(details.params.client_id) } }) : null;
const base = {
uid: details.uid,
stage,
product: client ? productName(client.product) : 'your account',
signupEnabled: await ctx.settings.bool('signup_enabled', true),
mfaRequested: mfaRequested(details),
loginHint: typeof details.params.login_hint === 'string' ? details.params.login_hint : null,
};
if (stage === 'password' || stage === 'done') return base;
const a = await account(ctx, pending);
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 });
}
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');
}
if (stage === 'setup_two_factor') {
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
extra.why = a.role === 'admin' ? 'admin' : 'product';
}
if (stage === 'notice') {
const n = await currentNotice(ctx);
extra.notice = { version: n.version, title: n.title, body: n.body };
extra.updated = a.noticeVersionAccepted > 0;
}
return { ...base, ...extra };
}
// ─── Steps ────────────────────────────────────────────────────────────────────
const CODE_ATTEMPTS = 5;
export async function submitPassword(ctx: Ctx, pending: PendingSignIn, input: { email?: unknown; password?: unknown; remember?: unknown }, req?: Request) {
const email = normaliseEmail(input.email);
const password = String(input.password ?? '');
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
const generic = new FlowError('That email address and password don\'t match.', 'BAD_CREDENTIALS', 401);
if (!a || a.status !== 'active' || !a.passwordHash) {
await verifyPassword(password, await dummyHash());
throw generic;
}
if (isLocked(ctx, a)) throw new FlowError(`Too many tries. Wait ${15} minutes, or reset your password.`, 'LOCKED', 429);
if (!(await verifyPassword(password, a.passwordHash))) {
await signInFailed(ctx, a, req);
throw generic;
}
await signInSucceeded(ctx, a);
if (needsRehash(a.passwordHash)) await ctx.db.account.update({ where: { id: a.id }, data: { passwordHash: await hashPassword(password) } });
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, stage: 'password', codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<string, unknown>) {
if (!(await ctx.settings.bool('signup_enabled', true))) throw new FlowError('New accounts are made by the church\'s office. Please ask them.', 'SIGNUP_OFF', 403);
const fields: Record<string, string> = {};
const name = String(input.name ?? '').trim().replace(/\s+/g, ' ');
const email = normaliseEmail(input.email);
const phone = input.phone ? normalisePhone(input.phone) : null;
if (name.length < 2 || name.length > 200) fields.name = 'Enter your name.';
const ep = emailProblem(email);
if (ep) fields.email = ep;
const pp = passwordProblem(input.password);
if (pp) fields.password = pp;
if (input.phone && !phone) fields.phone = 'Enter a phone number like 082 123 4567.';
if (input.acceptNotice !== true) fields.acceptNotice = 'Please read and accept the privacy notice.';
if (Object.keys(fields).length) throw new FlowError('Some details need fixing.', 'VALIDATION', 400, fields);
if (await ctx.db.account.findUnique({ where: { email } })) {
throw new FlowError('There\'s already an account with that email address. Sign in, or reset your password if you\'ve forgotten it.', 'EXISTS', 409, { email: 'Already has an account.' });
}
const notice = await currentNotice(ctx);
const parts = name.split(' ');
const a = await ctx.db.account.create({
data: {
name, givenName: parts[0] ?? null, familyName: parts.length > 1 ? parts.slice(1).join(' ') : null, email, phone,
passwordHash: await hashPassword(String(input.password)), noticeVersionAccepted: notice.version, lastSignInAt: ctx.now(),
},
});
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
await loginEvent(ctx, a.id, 'account_created');
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
}
async function checkCode(ctx: Ctx, pending: PendingSignIn, code: unknown) {
if (!pending.codeHash || !pending.codeSentAt || ctx.now().getTime() - pending.codeSentAt.getTime() > CODE_MINUTES * 60e3) {
throw new FlowError('That code has expired. Send a new one.', 'CODE_EXPIRED', 400);
}
if (pending.attempts >= CODE_ATTEMPTS) throw new FlowError('Too many wrong codes. Send a new one.', 'TOO_MANY', 429);
if (!codeMatches(code, pending.codeHash)) {
await save(ctx, pending, { attempts: pending.attempts + 1 });
throw new FlowError('That code isn\'t right.', 'BAD_CODE', 400);
}
}
export async function resendCode(ctx: Ctx, pending: PendingSignIn) {
if (pending.codeSentAt && ctx.now().getTime() - pending.codeSentAt.getTime() < 30e3) throw new FlowError('Wait half a minute before asking for another code.', 'TOO_SOON', 429);
return save(ctx, pending, { codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function verifyEmail(ctx: Ctx, pending: PendingSignIn, code: unknown) {
await checkCode(ctx, pending, code);
await ctx.db.account.update({ where: { id: pending.accountId! }, data: { emailVerified: true } });
return save(ctx, pending, { codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function twoFactor(ctx: Ctx, pending: PendingSignIn, input: { code?: unknown; recoveryCode?: unknown }, req?: Request) {
const a = await account(ctx, pending);
if (input.recoveryCode) {
if (!(await useRecoveryCode(ctx, a, input.recoveryCode, req))) throw new FlowError('That recovery code isn\'t right, or it was used already.', 'BAD_CODE', 400);
} else if (a.twoFactorMethod === 'totp') {
if (pending.attempts >= CODE_ATTEMPTS) throw new FlowError('Too many wrong codes. Wait a few minutes.', 'TOO_MANY', 429);
if (!(await verifyTotp(ctx, a, input.code))) {
await save(ctx, pending, { attempts: pending.attempts + 1 });
throw new FlowError('That code isn\'t right. Check your authenticator app\'s time is correct.', 'BAD_CODE', 400);
}
} else {
await checkCode(ctx, pending, input.code);
}
return save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function setupStart(ctx: Ctx, pending: PendingSignIn, method: unknown) {
const a = await account(ctx, pending);
const started = await startTwoFactorSetup(ctx, a, method);
await save(ctx, pending, { pendingTotpSecret: started.encryptedSecret, codeHash: started.codeHash, codeSentAt: started.codeHash ? ctx.now() : null, attempts: 0 });
return started.forScreen;
}
export async function setupConfirm(ctx: Ctx, pending: PendingSignIn, input: { method?: unknown; code?: unknown }, req?: Request) {
const a = await account(ctx, pending);
const recoveryCodes = await confirmTwoFactorSetup(ctx, a, { method: input.method, code: input.code, pendingSecret: pending.pendingTotpSecret, codeHash: pending.codeHash, codeSentAt: pending.codeSentAt }, req);
const next = await save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), pendingTotpSecret: null, codeHash: null, codeSentAt: null, attempts: 0 });
return { pending: next, recoveryCodes };
}
export async function notice(ctx: Ctx, pending: PendingSignIn, version: unknown) {
const current = await currentNotice(ctx);
if (Number(version) !== current.version) throw new FlowError('The notice changed while you were reading it. Please read it again.', 'STALE', 409);
await acceptNotice(ctx, pending.accountId!, current.version);
return pending;
}
export async function news(ctx: Ctx, pending: PendingSignIn, input: { email?: unknown; whatsapp?: unknown }) {
const a = await account(ctx, pending);
await setNewsConsent(ctx, a, { email: input.email === true, whatsapp: input.whatsapp === true && !!a.phone }, 'news_question');
return pending;
}
/** The result oidc-provider needs to finish the sign-in. */
export function loginResult(pending: PendingSignIn) {
const mfa = pending.amr.includes('mfa');
return { login: { accountId: pending.accountId!, amr: pending.amr, acr: mfa ? ACR_MFA : 'pwd', remember: pending.remember } };
}
@@ -0,0 +1,151 @@
/**
* The sign-in pages' API (`/api/v2/interaction/:uid/…`), forgot / reset password, and Accounts'
* own sign-in for the account page (`/api/self/…`, an OIDC client of itself).
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
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 { hashToken, randomToken } from '../lib/crypto.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { normaliseEmail } from '../accounts/service.js';
import { SELF_CALLBACK, SELF_CLIENT_ID } from '../oidc/clients.js';
import { issuerOf } from '../oidc/provider.js';
import * as flow from './flow.js';
const RESET_MINUTES = 60;
export function interactionRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
/** The interaction behind `uid`, from this browser's interaction cookie. */
async function load(req: Request, res: Response) {
let details;
try {
details = await provider.interactionDetails(req, res);
} catch {
throw new ApiError(410, 'EXPIRED', 'This sign-in has expired. Go back to the site you came from and sign in again.');
}
if (details.uid !== req.params.uid) throw new ApiError(410, 'EXPIRED', 'This sign-in has expired. Go back to the site you came from and sign in again.');
return { details, pending: await flow.pendingFor(ctx, details) };
}
/** After a step: the next step's page data, or the address to finish at (the product). */
async function next(req: Request, res: Response, extra: Record<string, unknown> = {}) {
const { details, pending } = await load(req, res);
const state = await flow.describe(ctx, details, pending);
if (state.stage !== 'done') return { ...state, ...extra };
const redirectTo = await provider.interactionResult(req, res, flow.loginResult(pending), { mergeWithLastSubmission: false });
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId: String(details.params.client_id ?? '') || null, detail: { amr: pending.amr } });
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
return { stage: 'done', redirectTo, ...extra };
}
const step = (fn: (req: Request, res: Response, pending: Awaited<ReturnType<typeof load>>['pending']) => Promise<Record<string, unknown> | void>) =>
handle(async (req, res) => {
const { pending } = await load(req, res);
const extra = (await fn(req, res, pending)) ?? {};
return next(req, res, extra);
});
// Where oidc-provider sends the browser (its cookie's path): on to the sign-in page.
r.get('/interaction/:uid', (req, res) => {
const uid = String(req.params.uid);
res.redirect(303, /^[A-Za-z0-9_-]{10,64}$/.test(uid) ? `/signin?uid=${uid}` : '/account');
});
// The page's state for the current step.
r.get('/interaction/:uid/state', handle(async (req, res) => next(req, res)));
r.post('/interaction/:uid/password', limit(20), step(async (req, _res, p) => { await flow.submitPassword(ctx, p, req.body ?? {}, req); }));
r.post('/interaction/:uid/signup', limit(10, 60), step(async (req, _res, p) => { await flow.signUp(ctx, p, req.body ?? {}); }));
r.post('/interaction/:uid/verify-email', limit(20), step(async (req, _res, p) => { await flow.verifyEmail(ctx, p, req.body?.code); }));
r.post('/interaction/:uid/two-factor', limit(20), step(async (req, _res, p) => { await flow.twoFactor(ctx, p, req.body ?? {}, req); }));
r.post('/interaction/:uid/resend', limit(10), step(async (_req, _res, p) => { await flow.resendCode(ctx, p); }));
r.post('/interaction/:uid/two-factor/setup', limit(10), handle(async (req, res) => {
const { pending } = await load(req, res);
return flow.setupStart(ctx, pending, req.body?.method);
}));
r.post('/interaction/:uid/two-factor/setup/confirm', limit(20), step(async (req, _res, p) => {
const { recoveryCodes } = await flow.setupConfirm(ctx, p, req.body ?? {}, req);
return { recoveryCodes };
}));
r.post('/interaction/:uid/notice', step(async (req, _res, p) => { await flow.notice(ctx, p, req.body?.version); }));
r.post('/interaction/:uid/news', step(async (req, _res, p) => { await flow.news(ctx, p, req.body ?? {}); }));
r.post('/interaction/:uid/cancel', handle(async (req, res) => {
await load(req, res);
const redirectTo = await provider.interactionResult(req, res, { error: 'access_denied', error_description: 'The person cancelled signing in.' }, { mergeWithLastSubmission: false });
return { stage: 'done', redirectTo };
}));
// ─── Forgot / reset password ───────────────────────────────────────────────
r.post('/password/forgot', limit(5), handle(async (req) => {
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).
if (a && a.status === 'active') {
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.`,
});
}
return { sent: true };
}));
r.post('/password/reset', limit(10), handle(async (req) => {
const token = String(req.body?.token ?? '');
const row = token ? await ctx.db.emailToken.findUnique({ where: { tokenHash: hashToken(token) } }) : null;
if (!row || row.purpose !== 'reset_password' || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used. Ask for a new one.');
const problem = passwordProblem(req.body?.password);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem });
await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null } });
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await ctx.db.emailToken.deleteMany({ where: { accountId: row.accountId, purpose: 'reset_password', usedAt: null } });
await loginEvent(ctx, row.accountId, 'password_reset', req);
// Back to the sign-in it started from, if this browser still has it (§5).
return { reset: true, uid: row.interactionUid };
}));
return r;
}
/**
* The account page signs in like any product: `/api/self/signin?returnTo=/account` starts an
* authorization request for `accounts-self`; the callback only needs the session the sign-in made.
*/
export function selfRouter(ctx: Ctx) {
const r = express.Router();
const callback = `${ctx.config.publicUrl}${SELF_CALLBACK}`;
r.get('/signin', (req, res) => {
const nonce = crypto.randomBytes(16).toString('base64url');
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const state = encodeState({ nonce, returnTo: safeReturnPath(req.query.returnTo, '/account') });
res.cookie('acc_self', nonce, { httpOnly: true, sameSite: 'lax', secure: ctx.config.production, maxAge: 3600e3, path: '/api/self' });
const url = new URL(`${issuerOf(ctx)}/auth`);
url.search = new URLSearchParams({
client_id: SELF_CLIENT_ID, response_type: 'code', scope: 'openid', redirect_uri: callback, state,
code_challenge: challenge, code_challenge_method: 'S256', nonce,
...(req.query.prompt === 'login' ? { prompt: 'login' } : {}),
...(req.query.acr === 'mfa' ? { acr_values: 'mfa' } : {}),
}).toString();
res.redirect(url.toString());
});
r.get('/callback', (req, res) => {
const state = decodeState(req.query.state);
const cookies = Object.fromEntries(String(req.get('cookie') || '').split(';').map((c) => c.trim().split('=')).filter((p) => p.length === 2)) as Record<string, string>;
res.clearCookie('acc_self', { path: '/api/self' });
if (!state || state.nonce !== cookies.acc_self || req.query.error) return res.redirect('/account');
return res.redirect(safeReturnPath(state.returnTo, '/account'));
});
return r;
}
+54
View File
@@ -0,0 +1,54 @@
/**
* 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.
*/
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { heartbeat } from './hub/client.js';
import { runDue } from './links/deliveries.js';
import { deleteExpired } from './oidc/adapter.js';
import { runDeletionJob } from './privacy/deletion.js';
import { runExportsJob } from './privacy/export.js';
type Job = { name: string; cron: string; everyMs: number; run: (ctx: Ctx) => Promise<unknown> };
export 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: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
run: async (ctx) => {
const now = ctx.now();
const [oidc, pending, tokens, nonces] = await Promise.all([
deleteExpired(ctx),
ctx.db.pendingSignIn.deleteMany({ where: { expiresAt: { lt: now } } }),
ctx.db.emailToken.deleteMany({ where: { expiresAt: { lt: new Date(now.getTime() - 7 * 24 * 3600e3) } } }),
ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - 3600e3) } } }),
]);
return { oidc: oidc.count, pending: pending.count, tokens: tokens.count, nonces: nonces.count };
},
},
];
export async function startJobs(ctx: Ctx, connectionString: string): Promise<() => Promise<void>> {
if (!ctx.config.jobsEnabled) return async () => {};
const tz = ctx.config.timezone;
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); };
}
}
+48
View File
@@ -0,0 +1,48 @@
/**
* The admin audit log, the per-person sign-in log and the access log. Logging never breaks the
* action it records.
*/
import type { Request } from 'express';
import type { Ctx } from '../context.js';
export function clientIp(req: Request | undefined): string | null {
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
}
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
try {
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
} catch (e) {
console.error('[audit]', (e as Error).message);
}
}
export type LoginEventType =
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created';
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
try {
await ctx.db.loginEvent.create({
data: {
accountId,
type,
clientId: extra.clientId ?? null,
ip: clientIp(req),
userAgent: req?.get('user-agent')?.slice(0, 300) ?? null,
detail: (extra.detail ?? undefined) as never,
createdAt: ctx.now(),
},
});
} catch (e) {
console.error('[login-event]', (e as Error).message);
}
}
export async function accessLog(ctx: Ctx, actorId: string, targetId: string, action: 'view' | 'export', req?: Request) {
try {
await ctx.db.accessLog.create({ data: { actorId, targetId, action, ip: clientIp(req), createdAt: ctx.now() } });
} catch (e) {
console.error('[access-log]', (e as Error).message);
}
}
+51
View File
@@ -0,0 +1,51 @@
/**
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
* tests pass their own with `loadConfig({...})`.
*/
export type Config = {
/** The public address, e.g. https://accounts.hopefamily.co.za (no trailing slash). */
publicUrl: string;
port: number;
/** Encrypts secrets at rest and signs cookies. Generated on the server, never sent anywhere. */
secret: string;
production: boolean;
/** Behind nginx/frp: trust X-Forwarded-* (as Events' TRUST_PROXY). */
trustProxy: boolean;
hubUrl: string;
hubLicenceKey: string | null;
hubPublicKey: string | null;
hubAdminName: string | null;
hubAdminEmail: string | null;
timezone: string;
smtp: { host: string; port: number; user: string; pass: string; from: string; secure: boolean } | null;
/** Local testing only: linked products on http or private addresses. */
allowPrivateLinks: boolean;
jobsEnabled: boolean;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
const publicUrl = String(env.ACCOUNTS_URL || env.PUBLIC_URL || 'http://localhost:3200').replace(/\/+$/, '');
const production = env.NODE_ENV === 'production';
const secret = env.ACCOUNTS_SECRET || '';
if (production && secret.length < 32) throw new Error('ACCOUNTS_SECRET must be set (at least 32 characters) in production.');
return {
publicUrl,
port: Number(env.PORT || 5200),
secret: secret || 'development-only-secret-change-me-0123456789',
production,
trustProxy: bool(env.TRUST_PROXY, production),
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim() || null,
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
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,
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
jobsEnabled: bool(env.JOBS_ENABLED, true),
};
}
+53
View File
@@ -0,0 +1,53 @@
/**
* Secrets at rest (AES-256-GCM, as Events' utils/encryption.js), tokens and codes.
* The key comes from ACCOUNTS_SECRET; encrypted values start with "enc:".
*/
import crypto from 'node:crypto';
const SENTINEL = 'enc:';
export class Secrets {
private readonly key: Buffer;
constructor(secret: string) {
this.key = crypto.scryptSync(secret, 'crosscode-accounts-aes256gcm-v1', 32);
}
encrypt(plain: string): string {
if (plain.startsWith(SENTINEL)) return plain;
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
}
/** Throws if the value was changed or encrypted with another key. */
decrypt(value: string): string {
if (!value.startsWith(SENTINEL)) return value;
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
decipher.setAuthTag(Buffer.from(tag, 'hex'));
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
}
/** Keys for signing cookies (oidc-provider and our own), derived so they're stable per install. */
cookieKeys(): string[] {
return [crypto.createHmac('sha256', this.key).update('cookies-v1').digest('base64url')];
}
}
/** A random token for a link sent by email (32 bytes, base64url). */
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
/** A 6-digit code sent by email or WhatsApp. */
export const randomCode = () => String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
/** What's stored for a token or code: only its SHA-256. */
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
export function safeEqual(a: string, b: string): boolean {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && crypto.timingSafeEqual(x, y);
}
+94
View File
@@ -0,0 +1,94 @@
/**
* Email (SMTP, from the admin's settings or the server's .env) and WhatsApp (WAWP, as Cross
* Events). In tests a `MemoryMessenger` keeps what would have been sent.
*/
import nodemailer from 'nodemailer';
import type { Ctx } from '../context.js';
export type Email = { to: string; subject: string; text: string };
export type WhatsApp = { to: string; text: string };
export interface Messenger {
email(msg: Email): Promise<void>;
whatsapp(msg: WhatsApp): Promise<void>;
/** Whether WhatsApp is set up, so it's offered as a 2FA method. */
whatsappReady(): Promise<boolean>;
}
/** 0821234567 / +27 82 123 4567 → 27821234567 (South African mobiles; others as given, digits only). */
export function waNumber(raw: string): string | null {
let d = String(raw || '').replace(/\D/g, '');
if (d.startsWith('0') && d.length === 10) d = `27${d.slice(1)}`;
return d.length >= 10 && d.length <= 15 ? d : null;
}
export class LiveMessenger implements Messenger {
constructor(private readonly ctx: Pick<Ctx, 'settings' | 'config'>) {}
private async smtp() {
const s = this.ctx.settings;
const host = (await s.get('smtp_host')) || this.ctx.config.smtp?.host;
if (!host) return null;
const port = Number((await s.get('smtp_port')) || this.ctx.config.smtp?.port || 587);
return {
transport: nodemailer.createTransport({
host,
port,
secure: (await s.get('smtp_secure')) === 'true' || (this.ctx.config.smtp?.secure ?? port === 465),
auth: { user: (await s.get('smtp_user')) || this.ctx.config.smtp?.user || '', pass: (await s.get('smtp_pass')) || this.ctx.config.smtp?.pass || '' },
}),
from: (await s.get('smtp_from')) || this.ctx.config.smtp?.from || '',
};
}
async email(msg: Email): Promise<void> {
const smtp = await this.smtp();
if (!smtp) {
if (this.ctx.config.production) throw new Error('Email isn\'t set up (Admin → Email and WhatsApp).');
console.log(`[email] (no SMTP) to ${msg.to}: ${msg.subject}\n${msg.text}`);
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 });
}
async whatsappReady(): Promise<boolean> {
return !!((await this.ctx.settings.get('wawp_access_token')) && (await this.ctx.settings.get('wawp_instance_id')));
}
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}).`);
}
}
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); }
async whatsappReady() { return this.whatsappOn; }
/** 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)];
const m = /\b(\d{6})\b/.exec(all[all.length - 1] ?? '');
return m ? m[1]! : null;
}
/** The last link sent to `to` (tests). */
lastLink(to: string): string | null {
const e = this.emails.filter((x) => x.to === to).at(-1);
const m = /(https?:\/\/\S+)/.exec(e?.text ?? '');
return m ? m[1]! : null;
}
}
@@ -0,0 +1,43 @@
/**
* Passwords: Argon2id with Events' parameters. bcrypt hashes (imported from Cross Events, whose
* older accounts still have them) verify too, and `needsRehash` tells the caller to store a new
* Argon2id hash after a successful sign-in, as Events does.
*/
import argon2 from '@node-rs/argon2';
import bcrypt from 'bcryptjs';
const OPTIONS = { algorithm: 2 as const /* Argon2id */, memoryCost: 19456, timeCost: 2, parallelism: 1 };
const PREFIX = `$argon2id$v=19$m=${OPTIONS.memoryCost},t=${OPTIONS.timeCost},p=${OPTIONS.parallelism}$`;
export const MIN_PASSWORD_LENGTH = 8;
export const MAX_PASSWORD_LENGTH = 200;
export function hashPassword(password: string): Promise<string> {
return argon2.hash(password, OPTIONS);
}
export async function verifyPassword(password: string, hash: string | null | undefined): Promise<boolean> {
if (!hash) return false;
try {
if (hash.startsWith('$argon2')) return await argon2.verify(hash, password);
if (/^\$2[aby]\$/.test(hash)) return await bcrypt.compare(password, hash);
} catch {
return false;
}
return false;
}
export const needsRehash = (hash: string) => !hash.startsWith(PREFIX);
/** A hash to compare against when there's no account, so a missing account takes as long. */
let dummy: Promise<string> | null = null;
export function dummyHash(): Promise<string> {
if (!dummy) dummy = hashPassword('no-such-account-placeholder');
return dummy;
}
export function passwordProblem(password: unknown): string | null {
if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) return `Use at least ${MIN_PASSWORD_LENGTH} characters.`;
if (password.length > MAX_PASSWORD_LENGTH) return 'That password is too long.';
return null;
}
@@ -0,0 +1,27 @@
/**
* Recovery codes: 10 single-use codes each time 2FA is turned on, shown once ("abcd-efgh-jkmn").
* Only their hashes are kept. Letters that are easy to mix up are left out.
*/
import crypto from 'node:crypto';
import { hashToken } from './crypto.js';
const ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
export const RECOVERY_CODE_COUNT = 10;
function one(): string {
const chars = Array.from({ length: 12 }, () => ALPHABET[crypto.randomInt(0, ALPHABET.length)]);
return `${chars.slice(0, 4).join('')}-${chars.slice(4, 8).join('')}-${chars.slice(8).join('')}`;
}
export function newRecoveryCodes(): { codes: string[]; hashes: string[] } {
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, one);
return { codes, hashes: codes.map(hashRecoveryCode) };
}
/** As typed: case and dashes or spaces don't matter. */
export function normaliseRecoveryCode(input: unknown): string {
const clean = String(input ?? '').toLowerCase().replace(/[^a-z0-9]/g, '');
return clean.length === 12 ? `${clean.slice(0, 4)}-${clean.slice(4, 8)}-${clean.slice(8)}` : clean;
}
export const hashRecoveryCode = (code: string) => hashToken(normaliseRecoveryCode(code));
+71
View File
@@ -0,0 +1,71 @@
/**
* Site settings in `AppSetting` (key → string). Secret ones are encrypted at rest. A short cache
* keeps sign-in pages from reading the table on every request.
*/
import type { Ctx } from '../context.js';
/** Encrypted at rest; never sent to the browser. */
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
/** 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',
'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure',
'wawp_access_token', 'wawp_instance_id',
]);
const TTL_MS = 30_000;
export class Settings {
private cache = new Map<string, { value: string | null; at: number }>();
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
async get(key: string): Promise<string | null> {
const hit = this.cache.get(key);
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
let value = row?.value ?? null;
if (value !== null && SECRET_SETTINGS.has(key)) {
try {
value = this.ctx.secrets.decrypt(value);
} catch {
value = null;
}
}
this.cache.set(key, { value, at: Date.now() });
return value;
}
async bool(key: string, fallback: boolean): Promise<boolean> {
const v = await this.get(key);
return v === null || v === '' ? fallback : v === 'true';
}
async json<T>(key: string, fallback: T): Promise<T> {
const v = await this.get(key);
if (!v) return fallback;
try {
return JSON.parse(v) as T;
} catch {
return fallback;
}
}
async set(key: string, value: string | null): Promise<void> {
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
else {
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
}
this.cache.delete(key);
}
async setMany(values: Record<string, string | null>): Promise<void> {
for (const [k, v] of Object.entries(values)) await this.set(k, v);
}
forget(): void {
this.cache.clear();
}
}
+71
View File
@@ -0,0 +1,71 @@
/**
* Authenticator-app codes (RFC 6238: SHA-1, 6 digits, 30 seconds), as Cross Events 2.3 and the Hub,
* so secrets moved from Events keep working. `matchStep` returns the step a code belongs to, so a
* code that was used once is refused the second time.
*/
import crypto from 'node:crypto';
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
export const STEP = 30;
export function base32Encode(buf: Uint8Array): string {
let bits = 0;
let value = 0;
let out = '';
for (const byte of buf) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += BASE32[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
return out;
}
export function base32Decode(str: string): Buffer {
let bits = 0;
let value = 0;
const out: number[] = [];
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
const idx = BASE32.indexOf(ch);
if (idx === -1) continue;
value = (value << 5) | idx;
bits += 5;
if (bits >= 8) {
out.push((value >>> (bits - 8)) & 255);
bits -= 8;
}
}
return Buffer.from(out);
}
export const generateSecret = () => base32Encode(crypto.randomBytes(20));
export function codeAt(secret: string, counter: number): string {
const buf = Buffer.alloc(8);
buf.writeBigUInt64BE(BigInt(counter));
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
const offset = hmac[hmac.length - 1]! & 0xf;
const num = ((hmac[offset]! & 0x7f) << 24) | (hmac[offset + 1]! << 16) | (hmac[offset + 2]! << 8) | hmac[offset + 3]!;
return String(num % 1_000_000).padStart(6, '0');
}
/** The step `code` is right for (now, or one either side for clock drift), or null. Steps up to `afterStep` were used. */
export function matchStep(secret: string, code: unknown, { now = Date.now(), afterStep = -1 } = {}): number | null {
const clean = String(code ?? '').replace(/\D/g, '');
if (clean.length !== 6) return null;
const counter = Math.floor(now / 1000 / STEP);
for (const c of [counter - 1, counter, counter + 1]) {
if (c <= afterStep) continue;
if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c;
}
return null;
}
/** The otpauth:// link an authenticator app scans as a QR code. */
export function otpauthUrl(secret: string, account: string, issuer: string): string {
const label = `${issuer}:${account}`;
return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
}
+22
View File
@@ -0,0 +1,22 @@
/**
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
* however the process was started (PM2 doesn't set npm_package_version).
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
let cached: string | null = null;
export function appVersion(): string {
if (!cached) {
try {
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
} catch {
cached = '0.0.0';
}
}
return cached;
}
+133
View File
@@ -0,0 +1,133 @@
/**
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4). On Accounts a link is also the
* product's **OIDC client** (docs/ACCOUNTS-1.0-PLAN.md §4, oidc/clients.ts): connecting registers
* it, disconnecting removes it. Usually the product connects (an admin there clicks Connect on
* Accounts); an Accounts admin can connect from here too.
*/
import {
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
} from '@crosscode/contracts';
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { audit, clientIp } from '../lib/audit.js';
import { callSibling, LinkCallError, siblingUrl } from './http.js';
import { keyPair, listedProduct } from './store.js';
export class LinkError extends Error {
constructor(message: string, public code: string, public status = 400) {
super(message);
}
}
/** Products that sign people in through Accounts. */
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
async function self(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
if (!installId) throw new LinkError('Accounts isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
const { privateKeyPem } = await keyPair(ctx);
return { installId, url: ctx.config.publicUrl, privateKeyPem };
}
const party = (s: { installId: string; url: string }) => ({ product: 'accounts' as const, installId: s.installId, url: s.url });
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
const now = ctx.now();
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
try {
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
return true;
} catch (e) {
if ((e as { code?: string }).code === 'P2002') return false;
throw e;
}
}
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById };
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
}
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, req: Request | undefined, by: string) =>
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
const sibling = await listedProduct(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
}, me.privateKeyPem);
let reply: unknown;
try {
reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
} catch (e) {
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
throw e;
}
const parsed = linkConnectedSchema.safeParse(reply);
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way Accounts doesn't understand.`, 'BAD_REPLY', 502);
const r: LinkConnected = parsed.data;
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
}
const link = await saveLink(ctx, sibling, secret, actor.id);
await logLink(ctx, 'product_link_connected', link, actor, req, 'accounts');
return link;
}
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise<LinkConnected> {
const parsed = linkConnectSchema.safeParse(body);
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
const link = await saveLink(ctx, sibling, m.secret, null);
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
return signLink<Omit<LinkConnected, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
}, me.privateKeyPem);
}
export async function disconnectFrom(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
const link = await ctx.db.productLink.findUnique({ where: { installId } });
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
let told = false;
let problem: string | null = null;
try {
const me = await self(ctx);
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
told = true;
} catch (e) {
problem = (e as Error).message;
}
await ctx.db.productLink.delete({ where: { installId } });
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'accounts');
return { told, problem };
}
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise<void> {
const parsed = linkDisconnectSchema.safeParse(body);
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
const m = parsed.data;
const me = await self(ctx);
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
if (!link) return;
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
await ctx.db.productLink.delete({ where: { installId: link.installId } });
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
}
@@ -0,0 +1,69 @@
/**
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
* export).
*/
import crypto from 'node:crypto';
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { callSibling, siblingUrl } from './http.js';
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
const links = await ctx.db.productLink.findMany(opts.linkIds ? { where: { installId: { in: opts.linkIds } } } : undefined);
const made = [];
for (const link of links) {
const callId = crypto.randomUUID();
made.push(await ctx.db.delivery.create({
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
}));
}
return made;
}
type ReplyHandler = (ctx: Ctx, delivery: { id: string; linkId: string; type: string; body: unknown }, reply: unknown) => Promise<void>;
const handlers = new Map<string, ReplyHandler>();
/** What to do with a product's answer to a call type (privacy/deletion.ts, privacy/export.ts). */
export function onReply(type: CallType, handler: ReplyHandler) {
handlers.set(type, handler);
}
export async function send(ctx: Ctx, deliveryId: string): Promise<boolean> {
const d = await ctx.db.delivery.findUnique({ where: { id: deliveryId } });
if (!d || d.status !== 'pending') return false;
const link = await ctx.db.productLink.findUnique({ where: { installId: d.linkId } });
const sender = await ctx.settings.get('hub_install_id');
const attempts = d.attempts + 1;
try {
if (!link || !sender) throw new Error(link ? 'Accounts isn\'t connected to the Hub' : 'The product is no longer linked');
const raw = JSON.stringify(d.body);
const headers = signedHeaders(LINK_HEADERS, { senderId: sender, secret: ctx.secrets.decrypt(link.secret), rawBody: raw, now: ctx.now() });
const reply = await callSibling(await siblingUrl(ctx, link.url, d.path), { method: 'POST', body: raw, headers });
await ctx.db.delivery.update({ where: { id: d.id }, data: { status: 'delivered', attempts, deliveredAt: ctx.now(), reply: (reply ?? null) as never, lastError: null } });
await handlers.get(d.type)?.(ctx, d, reply);
return true;
} catch (e) {
const failed = attempts >= MAX_ATTEMPTS || !link;
await ctx.db.delivery.update({
where: { id: d.id },
data: { attempts, lastError: String((e as Error).message).slice(0, 500), status: failed ? 'failed' : 'pending', nextAttemptAt: new Date(ctx.now().getTime() + (RETRY_MS[attempts - 1] ?? RETRY_MS.at(-1)!)) },
});
return false;
}
}
/** The `deliveries` job (every minute): everything due, oldest first. */
export async function runDue(ctx: Ctx, limit = 50) {
const due = await ctx.db.delivery.findMany({ where: { status: 'pending', nextAttemptAt: { lte: ctx.now() } }, orderBy: { nextAttemptAt: 'asc' }, take: limit });
let sent = 0;
for (const d of due) if (await send(ctx, d.id)) sent++;
return { due: due.length, sent };
}
+76
View File
@@ -0,0 +1,76 @@
/**
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
*/
import dns from 'node:dns/promises';
import net from 'node:net';
import type { Ctx } from '../context.js';
const TIMEOUT_MS = 15000;
const MAX_BYTES = 5 * 1024 * 1024;
export class LinkCallError extends Error {
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
super(message);
}
}
export function isPrivateAddress(ip: string): boolean {
if (net.isIPv4(ip)) {
const [a, b] = ip.split('.').map(Number) as [number, number];
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
}
if (net.isIPv6(ip)) {
const v = ip.toLowerCase();
if (v === '::1' || v === '::') return true;
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
if (mapped) return isPrivateAddress(mapped[1]!);
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
}
return true;
}
export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise<URL> {
let url: URL;
try {
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
} catch {
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
}
const allow = ctx.config.allowPrivateLinks;
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
if (!allow) {
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
}
return url;
}
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
let res: Response;
try {
res = await fetch(url, {
method: init.method,
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
body: init.body,
redirect: 'manual',
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch (e) {
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE');
}
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
const text = await res.text();
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
let data: unknown = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
}
if (!res.ok) {
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
}
return data;
}
+34
View File
@@ -0,0 +1,34 @@
/**
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
* hub_linked_products.
*/
import { hub } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
type LinkedProduct = hub.LinkedProduct;
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
const pair = generateEd25519();
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
}
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
}
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
if (!Array.isArray(list)) return;
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
}
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
}
+212
View File
@@ -0,0 +1,212 @@
/**
* The account page's API (`/api/v2/me/…`): profile, password, 2FA, sign-ins, news consent,
* download my data, delete my account, sign out everywhere. Signed in with the Accounts session.
*/
import fs from 'node:fs/promises';
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 { loginEvent } from '../lib/audit.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';
import { currentSession, signOutEverywhere, type SignedIn } from '../oidc/sessions.js';
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';
export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: number; noticeVersion: number }) {
return {
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified,
phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
};
}
export function meRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
const signedIn = async (req: Request, res: Response) => {
const s = await currentSession(ctx, provider, req, res);
if (!s) throw new ApiError(401, 'UNAUTHENTICATED', 'Please sign in.');
return s;
};
const view = async (s: SignedIn) => {
const a = (await ctx.db.account.findUnique({ where: { id: s.account.id } }))!;
return meView(a, { recoveryCodesLeft: await recoveryCodesLeft(ctx, a.id), noticeVersion: (await currentNotice(ctx)).version });
};
const needPassword = async (s: SignedIn, password: unknown) => {
if (!(await verifyPassword(String(password ?? ''), s.account.passwordHash))) throw new ApiError(400, 'BAD_PASSWORD', 'That isn\'t your current password.', { password: 'That isn\'t your current password.' });
};
r.get('/me', handle(async (req, res) => view(await signedIn(req, res))));
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;
if (name.length < 2 || name.length > 200) throw new ApiError(400, 'VALIDATION', 'Enter your name.', { name: 'Enter your name.' });
const phone = req.body?.phone !== undefined ? (req.body.phone ? normalisePhone(req.body.phone) : null) : s.account.phone;
if (req.body?.phone && !phone) throw new ApiError(400, 'VALIDATION', 'Enter a phone number like 082 123 4567.', { phone: 'Enter a phone number like 082 123 4567.' });
const parts = name.split(' ');
await ctx.db.account.update({
where: { id: s.account.id },
data: {
name, givenName: req.body?.givenName ?? parts[0] ?? null, familyName: req.body?.familyName ?? (parts.length > 1 ? parts.slice(1).join(' ') : null), phone,
...(phone !== s.account.phone ? { phoneVerified: false } : {}),
// No phone, no WhatsApp news.
...(phone ? {} : { newsWhatsApp: false }),
},
});
await profileChanged(ctx, s.account.id);
return view(s);
}));
// A new email address is confirmed by a link sent to it; the old one keeps working until then.
r.post('/me/email', limit(5), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
const email = normaliseEmail(req.body?.email);
const problem = emailProblem(email);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { email: problem });
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.` });
return { sent: true };
}));
r.post('/me/email/confirm', handle(async (req, res) => {
const s = await signedIn(req, res);
const row = await ctx.db.emailToken.findUnique({ where: { tokenHash: hashToken(String(req.body?.token ?? '')) } });
if (!row || row.accountId !== s.account.id || !row.purpose.startsWith('change_email:') || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used.');
const email = row.purpose.slice('change_email:'.length);
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 loginEvent(ctx, s.account.id, 'email_changed', req);
await profileChanged(ctx, s.account.id);
return view(s);
}));
r.post('/me/password', limit(10), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.current);
const problem = passwordProblem(req.body?.password);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem });
await ctx.db.account.update({ where: { id: s.account.id }, data: { passwordHash: await hashPassword(String(req.body.password)) } });
await loginEvent(ctx, s.account.id, 'password_changed', req);
return { changed: true };
}));
// ─── Two-factor ────────────────────────────────────────────────────────────
const setupKey = (id: string) => `me:${id}`;
r.post('/me/two-factor/setup', limit(10), handle(async (req, res) => {
const s = await signedIn(req, res);
const started = await startTwoFactorSetup(ctx, s.account, req.body?.method);
const data = { uid: setupKey(s.account.id), accountId: s.account.id, stage: 'setup', pendingTotpSecret: started.encryptedSecret, codeHash: started.codeHash, codeSentAt: started.codeHash ? ctx.now() : null, amr: [], attempts: 0, expiresAt: new Date(ctx.now().getTime() + 3600e3) };
await ctx.db.pendingSignIn.upsert({ where: { uid: data.uid }, create: data, update: data });
return started.forScreen;
}));
r.post('/me/two-factor/confirm', limit(20), handle(async (req, res) => {
const s = await signedIn(req, res);
const p = await ctx.db.pendingSignIn.findUnique({ where: { uid: setupKey(s.account.id) } });
if (!p || p.expiresAt < ctx.now()) throw new ApiError(400, 'RESTART', 'Start setting it up again.');
const recoveryCodes = await confirmTwoFactorSetup(ctx, s.account, { method: req.body?.method, code: req.body?.code, pendingSecret: p.pendingTotpSecret, codeHash: p.codeHash, codeSentAt: p.codeSentAt }, req);
await ctx.db.pendingSignIn.deleteMany({ where: { uid: p.uid } });
await profileChanged(ctx, s.account.id);
return { ...(await view(s)), recoveryCodes };
}));
r.post('/me/two-factor/off', limit(10), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
if (s.account.role === 'admin' && (await ctx.settings.bool('two_factor_required_for_admins', true))) throw new ApiError(400, 'REQUIRED', 'Admins must keep two-factor sign-in on. You can change how you get your codes instead.');
await turnOff(ctx, s.account.id);
await loginEvent(ctx, s.account.id, 'two_factor_off', req);
await profileChanged(ctx, s.account.id);
return view(s);
}));
r.post('/me/recovery-codes', limit(5), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
if (!s.account.twoFactorMethod) throw new ApiError(400, 'NO_2FA', 'Turn on two-factor sign-in first.');
const codes = await replaceRecoveryCodes(ctx, s.account.id);
await loginEvent(ctx, s.account.id, 'recovery_codes_replaced', req);
return { recoveryCodes: codes };
}));
// ─── Activity, consent, privacy ─────────────────────────────────────────────
r.get('/me/sign-ins', handle(async (req, res) => {
const s = await signedIn(req, res);
const events = await ctx.db.loginEvent.findMany({ where: { accountId: s.account.id }, orderBy: { createdAt: 'desc' }, take: 50 });
const links = await ctx.db.productLink.findMany();
const names = new Map(links.map((l) => [l.installId, l.url]));
return { items: events.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent, site: e.clientId ? names.get(e.clientId) ?? null : null })) };
}));
r.put('/me/news', handle(async (req, res) => {
const s = await signedIn(req, res);
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page');
if (changed) await profileChanged(ctx, s.account.id);
return view(s);
}));
r.get('/me/notice', handle(async (req, res) => {
await signedIn(req, res);
const n = await currentNotice(ctx);
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
}));
r.post('/me/sign-out-everywhere', handle(async (req, res) => {
const s = await signedIn(req, res);
const told = await signOutEverywhere(ctx, provider, s.account.id);
await loginEvent(ctx, s.account.id, 'signed_out_everywhere', req, { detail: { productsTold: told } });
return { signedOut: true };
}));
r.get('/me/exports', handle(async (req, res) => {
const s = await signedIn(req, res);
const list = await ctx.db.dataExport.findMany({ where: { accountId: s.account.id }, orderBy: { createdAt: 'desc' }, take: 5 });
return { items: list.map((e) => ({ id: e.id, status: e.status, createdAt: e.createdAt, readyAt: e.readyAt, expiresAt: e.expiresAt })) };
}));
r.post('/me/exports', limit(3, 60), handle(async (req, res) => {
const s = await signedIn(req, res);
const e = await requestExport(ctx, s.account.id);
return { id: e.id, status: (await ctx.db.dataExport.findUnique({ where: { id: e.id } }))!.status };
}));
r.get('/me/exports/:id/download', async (req, res) => {
try {
const s = await signedIn(req, res);
const e = await ctx.db.dataExport.findUnique({ where: { id: String(req.params.id) } });
if (!e || e.accountId !== s.account.id || e.status !== 'ready' || !e.file) throw new ApiError(404, 'NOT_FOUND', 'That download isn\'t available any more.');
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="my-data-${e.createdAt.toISOString().slice(0, 10)}.json"`);
res.send(await fs.readFile(e.file));
} catch (err) {
const { sendError } = await import('../http.js');
sendError(res, err);
}
});
r.post('/me/delete', limit(3, 60), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
const admins = await ctx.db.account.count({ where: { role: 'admin', status: 'active' } });
if (s.account.role === 'admin' && admins <= 1) throw new ApiError(400, 'LAST_ADMIN', 'You\'re the only admin. Make someone else an admin first.');
await requestDeletion(ctx, provider, s.account.id, req);
return { requested: true };
}));
return r;
}
+69
View File
@@ -0,0 +1,69 @@
/**
* oidc-provider's storage in Postgres (`OidcPayload`, one row per model and id), so sessions and
* codes survive restarts and work with more than one process. Clients aren't stored here: they're
* the linked products (oidc/clients.ts).
*/
import type { Adapter, AdapterPayload } from 'oidc-provider';
import type { Ctx } from '../context.js';
import { clientMetadataFor } from './clients.js';
/** Models whose rows are found by grant (revoked together). */
const GRANTABLE = new Set(['AccessToken', 'AuthorizationCode', 'RefreshToken', 'DeviceCode', 'BackchannelAuthenticationRequest']);
export function adapterFor(ctx: Ctx) {
return class PrismaAdapter implements Adapter {
constructor(private readonly model: string) {}
private key(id: string) {
return `${this.model}:${id}`;
}
async upsert(id: string, payload: AdapterPayload, expiresIn: number): Promise<void> {
const data = {
model: this.model,
payload: payload as never,
grantId: payload.grantId ?? null,
userCode: payload.userCode ?? null,
uid: payload.uid ?? null,
accountId: this.model === 'Session' ? (payload.accountId ?? null) : null,
expiresAt: expiresIn ? new Date(ctx.now().getTime() + expiresIn * 1000) : null,
};
await ctx.db.oidcPayload.upsert({ where: { id: this.key(id) }, create: { id: this.key(id), ...data }, update: data });
}
private live(row: { payload: unknown; expiresAt: Date | null; consumedAt: Date | null } | null): AdapterPayload | undefined {
if (!row || (row.expiresAt && row.expiresAt <= ctx.now())) return undefined;
return { ...(row.payload as AdapterPayload), ...(row.consumedAt ? { consumed: Math.floor(row.consumedAt.getTime() / 1000) } : {}) };
}
async find(id: string): Promise<AdapterPayload | undefined> {
if (this.model === 'Client') return (await clientMetadataFor(ctx, id)) as AdapterPayload | undefined;
return this.live(await ctx.db.oidcPayload.findUnique({ where: { id: this.key(id) } }));
}
async findByUserCode(userCode: string) {
return this.live(await ctx.db.oidcPayload.findFirst({ where: { model: this.model, userCode } }));
}
async findByUid(uid: string) {
return this.live(await ctx.db.oidcPayload.findFirst({ where: { model: this.model, uid } }));
}
async consume(id: string) {
await ctx.db.oidcPayload.update({ where: { id: this.key(id) }, data: { consumedAt: ctx.now() } }).catch(() => {});
}
async destroy(id: string) {
await ctx.db.oidcPayload.deleteMany({ where: { id: this.key(id) } });
}
async revokeByGrantId(grantId: string) {
if (GRANTABLE.has(this.model) || this.model === 'Grant') await ctx.db.oidcPayload.deleteMany({ where: { grantId } });
}
};
}
/** The `oidc-cleanup` job: rows past their expiry. */
export async function deleteExpired(ctx: Ctx) {
return ctx.db.oidcPayload.deleteMany({ where: { expiresAt: { lt: ctx.now() } } });
}
+51
View File
@@ -0,0 +1,51 @@
/**
* OIDC clients (docs/ACCOUNTS-1.0-PLAN.md §4): every linked product is one, with no registration
* screen. `client_id` is its Hub install id, the secret is derived from its link's secret, and its
* addresses are the fixed paths on the address the Hub listed for it (exact matches only).
*
* Plus Accounts' own pages (`accounts-self`): the account page signs in through the same flow.
*/
import { oidcClientAddresses } from '@crosscode/contracts';
import { oidcClientSecret } from '@crosscode/contracts/signing';
import type { ClientMetadata } from 'oidc-provider';
import type { Ctx } from '../context.js';
export const SELF_CLIENT_ID = 'accounts-self';
export const SELF_CALLBACK = '/api/self/callback';
const PRODUCT_NAMES: Record<string, string> = { events: 'Cross Events', website: 'the church website', app: 'the church app' };
export function selfClient(ctx: Ctx): ClientMetadata {
return {
client_id: SELF_CLIENT_ID,
client_name: 'Your account',
token_endpoint_auth_method: 'none',
grant_types: ['authorization_code'],
response_types: ['code'],
redirect_uris: [`${ctx.config.publicUrl}${SELF_CALLBACK}`],
post_logout_redirect_uris: [`${ctx.config.publicUrl}/signed-out`],
};
}
export async function clientMetadataFor(ctx: Ctx, clientId: string): Promise<ClientMetadata | undefined> {
const link = await ctx.db.productLink.findUnique({ where: { installId: clientId } }).catch(() => null);
if (!link) return undefined;
const a = oidcClientAddresses(link.url);
return {
client_id: link.installId,
client_secret: oidcClientSecret(ctx.secrets.decrypt(link.secret)),
client_name: PRODUCT_NAMES[link.product] ?? link.product,
token_endpoint_auth_method: 'client_secret_basic',
grant_types: ['authorization_code'],
response_types: ['code'],
redirect_uris: [a.redirectUri],
post_logout_redirect_uris: [a.postLogoutRedirectUri],
backchannel_logout_uri: a.backchannelLogoutUri,
backchannel_logout_session_required: true,
'crosscode.product': link.product,
} as ClientMetadata;
}
export function productName(product: string | undefined): string {
return (product && PRODUCT_NAMES[product]) || 'this site';
}
+51
View File
@@ -0,0 +1,51 @@
/**
* The few pages oidc-provider renders itself (an error, the sign-out confirmation, "signed out"),
* in the church's colours. No inline scripts (the CSP forbids them): the sign-out page submits
* itself with /api/static/logout.js.
*/
import type { KoaContextWithOIDC } from 'oidc-provider';
import type { Ctx } from '../context.js';
import { branding } from '../church/profile.js';
const esc = (s: unknown) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
async function page(ctx: Ctx, title: string, body: string): Promise<string> {
const b = await branding(ctx).catch(() => ({ name: 'Sign in', colours: { primary: '#1f4e79' }, logoUrl: null }));
return `<!doctype html><html lang="en-ZA"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
<title>${esc(title)} · ${esc(b.name)}</title>
<style>body{font-family:system-ui,sans-serif;background:#f7f7f8;color:#1f2937;margin:0;display:flex;min-height:100vh;align-items:center;justify-content:center;padding:16px}
main{background:#fff;border-radius:16px;box-shadow:0 1px 3px rgba(0,0,0,.08);padding:32px;max-width:420px;width:100%;text-align:center}
h1{font-size:1.25rem;margin:0 0 12px}p{color:#4b5563;line-height:1.5}button,a.btn{display:inline-block;background:${esc(b.colours.primary)};color:#fff;border:0;border-radius:10px;padding:10px 20px;font-size:1rem;text-decoration:none;cursor:pointer}
img{max-height:56px;margin-bottom:16px}</style></head>
<body><main>${b.logoUrl ? `<img src="${esc(b.logoUrl)}" alt="">` : ''}<p style="margin:0 0 8px;font-weight:600">${esc(b.name)}</p>${body}</main></body></html>`;
}
export function renderError(ctx: Ctx) {
return async (k: KoaContextWithOIDC, out: { error: string; error_description?: string }, err?: Error) => {
console.warn(`[oidc] ${out.error}: ${out.error_description ?? ''}${err && !(err as { expose?: boolean }).expose ? ` (${err.stack})` : ''}`);
k.type = 'html';
const message = out.error === 'invalid_redirect_uri' || out.error === 'invalid_client'
? 'This sign-in link isn\'t from one of the church\'s sites, so it was stopped.'
: out.error_description || 'Something went wrong with signing in.';
k.body = await page(ctx, 'Sign-in problem', `<h1>We couldn't sign you in</h1><p>${esc(message)}</p><a class="btn" href="/account">Go to your account</a>`);
};
}
export function renderLogout(ctx: Ctx) {
return async (k: KoaContextWithOIDC, form: string) => {
k.type = 'html';
k.body = await page(ctx, 'Signing out', `${form}<h1>Signing you out…</h1><p>You'll be signed out of all the church's sites.</p>
<button form="op.logoutForm" type="submit" name="logout" value="yes">Sign out</button>
<script src="/api/static/logout.js"></script>`);
};
}
export function renderLoggedOut(ctx: Ctx) {
return async (k: KoaContextWithOIDC) => {
k.type = 'html';
k.body = await page(ctx, 'Signed out', '<h1>You\'re signed out</h1><p>You\'ve been signed out of all the church\'s sites.</p><a class="btn" href="/account">Sign in again</a>');
};
}
/** Submits the sign-out form straight away (the person already chose to sign out on the product). */
export const LOGOUT_JS = 'document.addEventListener("DOMContentLoaded",function(){var f=document.getElementById("op.logoutForm");if(f){var i=document.createElement("input");i.type="hidden";i.name="logout";i.value="yes";f.appendChild(i);f.submit();}});';
+142
View File
@@ -0,0 +1,142 @@
/**
* The OpenID Connect provider (oidc-provider 9, docs/ACCOUNTS-1.0-PLAN.md §3): authorization code
* with PKCE (S256) for every client, no implicit or hybrid flows, no refresh tokens, ES256 keys
* made on first start, `crosscode.identity/1` claims, RP-initiated and back-channel logout.
*
* Sign-in steps happen in our own pages (interaction/): the provider sends people to
* `/signin?uid=…`. Products of the church are first-party, so there's no consent screen: a grant
* for the scopes asked for is made when they sign in (`loadExistingGrant`).
*/
import crypto from 'node:crypto';
import Provider, { interactionPolicy, type Configuration, type KoaContextWithOIDC } from 'oidc-provider';
import { ACR_MFA, OIDC_PROVIDER_PATHS, OIDC_SCOPES } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { identityClaims } from '../accounts/service.js';
import { currentNoticeVersion } from '../privacy/notice.js';
import { adapterFor } from './adapter.js';
import { selfClient } from './clients.js';
import { renderError, renderLogout, renderLoggedOut } from './pages.js';
const DAY = 24 * 60 * 60;
export const issuerOf = (ctx: Ctx) => `${ctx.config.publicUrl}${OIDC_PROVIDER_PATHS.issuer}`;
type Jwk = crypto.JsonWebKey & { kid: string; alg: string; use: string };
/** The signing keys (newest first), made the first time. `rotateKeys` adds a new one. */
export async function signingKeys(ctx: Ctx): Promise<Jwk[]> {
const keys = await ctx.settings.json<Jwk[]>('oidc_jwks', []);
if (keys.length) return keys;
return rotateKeys(ctx);
}
/** A new ES256 key in front; the previous one stays for checking tokens it signed (they last minutes). */
export async function rotateKeys(ctx: Ctx): Promise<Jwk[]> {
const old = await ctx.settings.json<Jwk[]>('oidc_jwks', []);
const { privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
const jwk = { ...privateKey.export({ format: 'jwk' }), kid: crypto.randomBytes(8).toString('hex'), alg: 'ES256', use: 'sig' } as Jwk;
const keys = [jwk, ...old].slice(0, 2);
await ctx.settings.set('oidc_jwks', JSON.stringify(keys));
return keys;
}
/** The interaction policy: the usual login checks, plus ours (§2, §6). */
function policy(ctx: Ctx) {
const { base, Check } = interactionPolicy;
const p = base();
const login = p.get('login')!;
// A product asked for 2FA (`acr_values=mfa`) and this session signed in without it.
login.checks.add(new Check('mfa_required', 'This sign-in needs a second step', async (k: KoaContextWithOIDC) => {
const wanted = String(k.oidc.params?.acr_values ?? '').split(' ').includes(ACR_MFA);
return wanted && k.oidc.session?.acr !== ACR_MFA ? Check.REQUEST_PROMPT : Check.NO_NEED_TO_PROMPT;
}));
// A newer privacy notice since this person last accepted one, or their account changed.
login.checks.add(new Check('account_needs_attention', 'The privacy notice changed', async (k: KoaContextWithOIDC) => {
const sub = k.oidc.session?.accountId;
if (!sub) return Check.NO_NEED_TO_PROMPT;
const a = await ctx.db.account.findUnique({ where: { id: sub } });
if (!a || a.status !== 'active') return Check.REQUEST_PROMPT;
return a.noticeVersionAccepted < (await currentNoticeVersion(ctx)) ? Check.REQUEST_PROMPT : Check.NO_NEED_TO_PROMPT;
}));
return p;
}
export async function createProvider(ctx: Ctx): Promise<Provider> {
const keys = await signingKeys(ctx);
const sessionDays = Number((await ctx.settings.get('session_days')) || 30);
const config: Configuration = {
adapter: adapterFor(ctx),
clients: [selfClient(ctx)],
extraClientMetadata: { properties: ['crosscode.product'] },
clientDefaults: { id_token_signed_response_alg: 'ES256', grant_types: ['authorization_code'], response_types: ['code'], token_endpoint_auth_method: 'client_secret_basic' },
findAccount: async (_k, sub) => {
const a = await ctx.db.account.findUnique({ where: { id: sub } });
if (!a || a.status !== 'active') return undefined;
return { accountId: sub, claims: async () => identityClaims(ctx, a) as never };
},
claims: {
openid: ['sub', 'acr', 'amr', 'auth_time'],
profile: ['name', 'given_name', 'family_name'],
email: ['email', 'email_verified'],
phone: ['phone_number', 'phone_number_verified'],
crosscode: ['schema', 'news_consent', 'two_factor', 'privacy_notice_version'],
},
scopes: [...OIDC_SCOPES],
acrValues: ['pwd', ACR_MFA],
// The claims go in the ID token too, so a product has everything without calling userinfo.
conformIdTokenClaims: false,
responseTypes: ['code'],
pkce: { required: () => true },
features: {
devInteractions: { enabled: false },
rpInitiatedLogout: { enabled: true, logoutSource: renderLogout(ctx), postLogoutSuccessSource: renderLoggedOut(ctx) },
backchannelLogout: { enabled: true },
revocation: { enabled: true },
userinfo: { enabled: true },
},
// oidc-provider scopes the interaction cookie to this address's path, so it's the API's path for
// the sign-in (every step's call is under it); that address sends the browser on to the page
// (interaction/routes.ts). Absolute, so a proxy that doesn't keep the Host header can't send
// people to the backend's own port.
interactions: { url: (_k, interaction) => `${ctx.config.publicUrl}/api/v2/interaction/${interaction.uid}`, policy: policy(ctx) },
loadExistingGrant: async (k) => {
const grantId = k.oidc.result?.consent?.grantId || k.oidc.session!.grantIdFor(k.oidc.client!.clientId);
if (grantId) {
const existing = await k.oidc.provider.Grant.find(grantId);
if (existing) return existing;
}
// The church's own products: no consent screen.
const grant = new k.oidc.provider.Grant({ clientId: k.oidc.client!.clientId, accountId: k.oidc.session!.accountId! });
grant.addOIDCScope(OIDC_SCOPES.join(' '));
await grant.save();
return grant;
},
cookies: {
keys: ctx.secrets.cookieKeys(),
long: { signed: true, httpOnly: true, sameSite: 'lax' },
short: { signed: true, httpOnly: true, sameSite: 'lax' },
},
jwks: { keys: keys as never },
enabledJWA: { idTokenSigningAlgValues: ['ES256'], userinfoSigningAlgValues: ['ES256'] },
ttl: {
AccessToken: 600,
AuthorizationCode: 60,
IdToken: 600,
Interaction: 3600,
Grant: sessionDays * DAY,
// "Keep me signed in": `sessionDays`; otherwise until the browser closes (a transient cookie), at most a day.
Session: (_k, session) => (session.transient ? DAY : sessionDays * DAY),
},
renderError: renderError(ctx),
// oidc-provider refuses private addresses for back-channel logout (its SSRF protection). Local
// testing only (LINKS_ALLOW_PRIVATE): send without that check, as for the other link calls.
...(ctx.config.allowPrivateLinks && !ctx.config.production
? { fetch: (input: string | URL | Request, init?: RequestInit) => { const { dispatcher: _d, ...rest } = (init ?? {}) as RequestInit & { dispatcher?: unknown }; return fetch(input, rest); } }
: {}),
rotateRefreshToken: false,
issueRefreshToken: () => false,
};
const provider = new Provider(issuerOf(ctx), config);
provider.proxy = ctx.config.trustProxy;
return provider;
}
@@ -0,0 +1,45 @@
/**
* The Accounts session (oidc-provider's own cookie) for the account pages and admin, and signing
* someone out everywhere: every session of theirs ends, and each product that session signed in to
* is told by OIDC Back-Channel Logout (docs/ACCOUNTS-1.0-PLAN.md §3).
*/
import type { Request, Response } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
export type SignedIn = { account: Account; amr: string[]; acr: string | null; sessionId: string };
export async function currentSession(ctx: Ctx, provider: Provider, req: Request, res: Response): Promise<SignedIn | null> {
const k = provider.createContext(req, res);
const session = await provider.Session.get(k);
if (!session?.accountId) return null;
const account = await ctx.db.account.findUnique({ where: { id: session.accountId } });
if (!account || account.status !== 'active') return null;
return { account, amr: (session.amr as string[] | undefined) ?? [], acr: (session.acr as string | undefined) ?? null, sessionId: session.jti };
}
type StoredSession = { authorizations?: Record<string, { sid?: string; grantId?: string }> };
/** Ends every session of the account and tells the products. Returns how many products were told. */
export async function signOutEverywhere(ctx: Ctx, provider: Provider, accountId: string): Promise<number> {
const rows = await ctx.db.oidcPayload.findMany({ where: { model: 'Session', accountId } });
let told = 0;
for (const row of rows) {
const auths = (row.payload as StoredSession).authorizations ?? {};
for (const [clientId, auth] of Object.entries(auths)) {
if (auth.grantId) await ctx.db.oidcPayload.deleteMany({ where: { grantId: auth.grantId } });
try {
const client = await provider.Client.find(clientId);
if (client?.backchannelLogoutUri) {
await (client as unknown as { backchannelLogout(sub: string, sid: string): Promise<void> }).backchannelLogout(accountId, auth.sid ?? '');
told++;
}
} catch (e) {
console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message, (e as { cause?: Error }).cause?.message ?? '');
}
}
await ctx.db.oidcPayload.deleteMany({ where: { id: row.id } });
}
return told;
}
@@ -0,0 +1,112 @@
/**
* "Delete my account" (docs/ACCOUNTS-1.0-PLAN.md §6, as Cross Events): the account is deactivated
* and signed out everywhere at once; an admin approves; then every linked product gets
* `user.deleted`. A product that answers `deferred` (e.g. an open registration for an upcoming
* event) is asked again after its `retryAfter`. Once every product has answered `deleted`, the
* account is anonymised.
*/
import { IDENTITY_SCHEMA, userDeletedReplySchema } from '@crosscode/contracts';
import type { Request } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { onReply, queueCall } from '../links/deliveries.js';
import { signOutEverywhere } from '../oidc/sessions.js';
type ProductState = { status: 'pending' | 'deleted' | 'deferred'; reason?: string; retryAfter?: string; product?: string };
type States = Record<string, ProductState>;
export async function requestDeletion(ctx: Ctx, provider: Provider, accountId: string, req?: Request) {
const open = await ctx.db.deletionRequest.findFirst({ where: { accountId, status: { in: ['waiting_approval', 'approved'] } } });
await ctx.db.account.update({ where: { id: accountId }, data: { status: 'deactivated', deactivatedAt: ctx.now() } });
await signOutEverywhere(ctx, provider, accountId);
await loginEvent(ctx, accountId, 'signed_out_everywhere', req, { detail: { reason: 'deletion_requested' } });
return open ?? ctx.db.deletionRequest.create({ data: { accountId, requestedAt: ctx.now() } });
}
export async function cancelDeletion(ctx: Ctx, requestId: string, actor: { id: string; role: string }, req?: Request) {
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
if (!r || r.status !== 'waiting_approval') return null;
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'cancelled', completedAt: ctx.now() } });
await ctx.db.account.update({ where: { id: r.accountId }, data: { status: 'active', deactivatedAt: null } });
await audit(ctx, { actorId: actor.id, actorRole: actor.role, action: 'deletion_cancelled', targetType: 'account', targetId: r.accountId, ip: clientIp(req) });
return r;
}
export async function approveDeletion(ctx: Ctx, requestId: string, actor: { id: string; role: string }, req?: Request) {
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
if (!r || r.status !== 'waiting_approval') return null;
const links = await ctx.db.productLink.findMany();
const states: States = Object.fromEntries(links.map((l) => [l.installId, { status: 'pending', product: l.product }]));
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'approved', approvedAt: ctx.now(), approvedById: actor.id, products: states as never } });
await audit(ctx, { actorId: actor.id, actorRole: actor.role, action: 'deletion_approved', targetType: 'account', targetId: r.accountId, ip: clientIp(req) });
await askProducts(ctx, r.id, r.accountId, links.map((l) => l.installId));
await finishIfDone(ctx, r.id);
return r;
}
async function askProducts(ctx: Ctx, requestId: string, accountId: string, linkIds: string[]) {
if (!linkIds.length) return;
await queueCall(ctx, 'user.deleted', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.deleted', callId, occurredAt: ctx.now().toISOString(), sub: accountId, approvedAt: ctx.now().toISOString(), requestId }), { linkIds });
}
onReply('user.deleted', async (ctx, delivery, reply) => {
const body = delivery.body as { requestId?: string };
if (!body.requestId) return;
const r = await ctx.db.deletionRequest.findUnique({ where: { id: body.requestId } });
if (!r || r.status !== 'approved') return;
const parsed = userDeletedReplySchema.safeParse(reply);
const states = { ...(r.products as States) };
const prev = states[delivery.linkId] ?? { status: 'pending' };
states[delivery.linkId] = !parsed.success
? { ...prev, status: 'deferred', reason: 'The product answered in a way Accounts doesn\'t understand; asking again tomorrow.', retryAfter: new Date(ctx.now().getTime() + 24 * 3600e3).toISOString() }
: parsed.data.status === 'deleted'
? { ...prev, status: 'deleted' }
: { ...prev, status: 'deferred', reason: parsed.data.reason, retryAfter: parsed.data.retryAfter };
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { products: states as never } });
await finishIfDone(ctx, r.id);
});
/** Anonymises the account once every product has deleted its part. */
export async function finishIfDone(ctx: Ctx, requestId: string) {
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
if (!r || r.status !== 'approved') return false;
const states = r.products as States;
// A product disconnected since has nothing left to delete here.
const linked = new Set((await ctx.db.productLink.findMany({ select: { installId: true } })).map((l) => l.installId));
if (Object.entries(states).some(([id, s]) => linked.has(id) && s.status !== 'deleted')) return false;
await anonymise(ctx, r.accountId);
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'done', completedAt: ctx.now() } });
return true;
}
export async function anonymise(ctx: Ctx, accountId: string) {
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
await ctx.db.emailToken.deleteMany({ where: { accountId } });
await ctx.db.account.update({
where: { id: accountId },
data: {
name: 'Deleted account', givenName: null, familyName: null, email: `deleted-${accountId}@deleted.invalid`, emailVerified: false,
phone: null, phoneVerified: false, passwordHash: null, twoFactorMethod: null, totpSecret: null, totpLastStep: null,
newsEmail: false, newsWhatsApp: false, status: 'deleted', anonymisedAt: ctx.now(),
},
});
// Sign-in history held IP addresses and devices: gone with the person.
await ctx.db.loginEvent.deleteMany({ where: { accountId } });
}
/** The `deletions` job: ask products that deferred again once their `retryAfter` has passed. */
export async function runDeletionJob(ctx: Ctx) {
const open = await ctx.db.deletionRequest.findMany({ where: { status: 'approved' } });
let asked = 0;
for (const r of open) {
const states = { ...(r.products as States) };
const due = Object.entries(states).filter(([, s]) => s.status === 'deferred' && s.retryAfter && new Date(s.retryAfter) <= ctx.now()).map(([id]) => id);
if (!due.length) continue;
for (const id of due) states[id] = { ...states[id]!, status: 'pending' };
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { products: states as never } });
await askProducts(ctx, r.id, r.accountId, due);
asked += due.length;
}
return { asked };
}
@@ -0,0 +1,88 @@
/**
* "Download my data" (docs/ACCOUNTS-1.0-PLAN.md §6): Accounts' own part, plus a `user.export` call
* to every linked product; their answers (`crosscode.identity/1` export sections) are put together
* in one file. It's ready once every product has answered, or after 24 hours with the missing ones
* listed; the person gets an email and downloads it from their account page for 7 days.
*/
import fs from 'node:fs/promises';
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';
const WAIT_MS = 24 * 3600e3;
const KEEP_MS = 7 * 24 * 3600e3;
export const exportsDir = () => path.resolve(process.env.EXPORTS_DIR || 'exports');
type Parts = Record<string, unknown>;
async function ownPart(ctx: Ctx, accountId: string) {
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: accountId } });
const [signIns, consents, notices] = await Promise.all([
ctx.db.loginEvent.findMany({ where: { accountId }, orderBy: { createdAt: 'desc' }, take: 500 }),
ctx.db.consentChange.findMany({ where: { accountId }, orderBy: { createdAt: 'asc' } }),
ctx.db.noticeAcceptance.findMany({ where: { accountId }, orderBy: { acceptedAt: 'asc' } }),
]);
return {
product: 'accounts',
sections: [
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
],
};
}
export async function requestExport(ctx: Ctx, accountId: string) {
const open = await ctx.db.dataExport.findFirst({ where: { accountId, status: 'collecting' } });
if (open) return open;
const exp = await ctx.db.dataExport.create({ data: { accountId, parts: { accounts: await ownPart(ctx, accountId) } as never, createdAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + WAIT_MS + KEEP_MS) } });
await queueCall(ctx, 'user.export', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.export', callId, occurredAt: ctx.now().toISOString(), sub: accountId, exportId: exp.id }));
await finishIfComplete(ctx, exp.id);
return exp;
}
onReply('user.export', async (ctx, delivery, reply) => {
const parsed = userExportReplySchema.safeParse(reply);
const body = delivery.body as { exportId?: string };
if (!body.exportId) return;
const exp = await ctx.db.dataExport.findUnique({ where: { id: body.exportId } });
if (!exp || exp.status !== 'collecting') return;
const parts = { ...(exp.parts as Parts), [delivery.linkId]: parsed.success ? parsed.data : { error: 'The product answered in a way Accounts doesn\'t understand.' } };
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { parts: parts as never } });
await finishIfComplete(ctx, exp.id);
});
/** Writes the file and emails the person once every product answered (or the wait is over). */
export async function finishIfComplete(ctx: Ctx, exportId: string, force = false) {
const exp = await ctx.db.dataExport.findUnique({ where: { id: exportId } });
if (!exp || exp.status !== 'collecting') return false;
const links = await ctx.db.productLink.findMany();
const parts = exp.parts as Parts;
const missing = links.filter((l) => !(l.installId in parts));
if (missing.length && !force) return false;
const file = path.join(exportsDir(), `${exp.id}.json`);
await fs.mkdir(exportsDir(), { recursive: true });
await fs.writeFile(file, JSON.stringify({
schema: IDENTITY_SCHEMA, exportId: exp.id, generatedAt: ctx.now().toISOString(),
parts: Object.values(parts),
missing: missing.map((l) => ({ product: l.product, url: l.url, note: 'Didn\'t answer within 24 hours. Ask the church for this part.' })),
}, 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` });
return true;
}
/** The `exports` job: finish exports that waited long enough, delete expired files. */
export async function runExportsJob(ctx: Ctx) {
const stale = await ctx.db.dataExport.findMany({ where: { status: 'collecting', createdAt: { lt: new Date(ctx.now().getTime() - WAIT_MS) } } });
for (const e of stale) await finishIfComplete(ctx, e.id, true);
const expired = await ctx.db.dataExport.findMany({ where: { status: 'ready', expiresAt: { lt: ctx.now() } } });
for (const e of expired) {
if (e.file) await fs.rm(e.file, { force: true });
await ctx.db.dataExport.update({ where: { id: e.id }, data: { status: 'expired', file: null } });
}
return { finished: stale.length, expired: expired.length };
}
@@ -0,0 +1,45 @@
/**
* The privacy notice (ROADMAP-v3 §3, as Cross Events): versions an admin publishes, and who
* accepted which. Version 1 is the built-in notice; published versions are 2, 3, … Someone who
* accepted an older version is asked again before signing in to a product (§5 of the plan).
*/
import type { Ctx } from '../context.js';
import { church } from '../church/profile.js';
export const BUILT_IN_VERSION = 1;
export async function builtInNotice(ctx: Ctx) {
const c = await church(ctx);
const contact = c.contact.email ? ` You can reach us at ${c.contact.email}.` : '';
return {
version: BUILT_IN_VERSION,
title: `How ${c.name} 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'),
publishedAt: null as Date | null,
};
}
export async function currentNotice(ctx: Ctx) {
const latest = await ctx.db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
return latest ?? (await builtInNotice(ctx));
}
export async function currentNoticeVersion(ctx: Ctx): Promise<number> {
return (await currentNotice(ctx)).version;
}
export async function accept(ctx: Ctx, accountId: string, version: number) {
await ctx.db.noticeAcceptance.create({ data: { accountId, version, acceptedAt: ctx.now() } });
await ctx.db.account.update({ where: { id: accountId }, data: { noticeVersionAccepted: version } });
}
export async function publish(ctx: Ctx, input: { title: string; body: string }, actorId: string) {
const latest = await ctx.db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
const version = Math.max(BUILT_IN_VERSION, latest?.version ?? BUILT_IN_VERSION) + 1;
return ctx.db.privacyNotice.create({ data: { version, title: input.title, body: input.body, publishedAt: ctx.now(), publishedById: actorId } });
}
@@ -0,0 +1,57 @@
/**
* Public endpoints: the church's branding for the sign-in pages, the church profile for its
* products (`GET /api/church/v1`, contracts 1.5.0), and Connect (`/api/links/v1/*`, as Events 2.4).
*/
import express, { type Response } from 'express';
import { CHURCH_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { handle, limit } from '../http.js';
import { branding, church } from '../church/profile.js';
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
import { setupNeeded } from '../setup/routes.js';
import { currentNotice } from '../privacy/notice.js';
const strip = (p: string) => p.replace(/^\/api/, '');
function linkError(res: Response, e: unknown) {
if (e instanceof LinkError) return res.status(e.status).json({ message: e.message, code: e.code });
console.error('[links]', e);
return res.status(500).json({ message: 'Something went wrong.', code: 'SERVER_ERROR' });
}
export function publicRouter(ctx: Ctx) {
const r = express.Router();
const json = express.json({ limit: '16kb' });
r.get('/v2/branding', handle(async () => ({ ...(await branding(ctx)), setupNeeded: await setupNeeded(ctx) })));
// The privacy notice, for the sign-up page's link (public).
r.get('/v2/notice', handle(async () => {
const n = await currentNotice(ctx);
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
}));
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
res.set('Cache-Control', 'public, max-age=60');
return church(ctx);
}));
r.post(strip(LINK_PATHS.connect), limit(30), json, async (req, res) => {
try {
res.json(await acceptConnect(ctx, req.body, req));
} catch (e) {
linkError(res, e);
}
});
r.post(strip(LINK_PATHS.disconnect), limit(30), json, async (req, res) => {
try {
await acceptDisconnect(ctx, req.body, req);
res.json({ schema: LINK_SCHEMA, type: 'link.disconnected' });
} catch (e) {
linkError(res, e);
}
});
return r;
}
+70
View File
@@ -0,0 +1,70 @@
/**
* First run (`/setup`): the church's name, the first admin and (unless the Hub installed it with
* HUB_LICENCE_KEY) the licence key. Only while there's no admin. On a Hub install the first admin
* must use the email address the Hub was given (HUB_ADMIN_EMAIL), so nobody else can take it.
*/
import express from 'express';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { emailProblem, normaliseEmail } from '../accounts/service.js';
import { updateProfile } from '../church/profile.js';
import { connect as connectHub } from '../hub/client.js';
import { currentNotice } from '../privacy/notice.js';
export async function setupNeeded(ctx: Ctx): Promise<boolean> {
return (await ctx.db.account.count({ where: { role: 'admin', status: 'active' } })) === 0;
}
export function setupRouter(ctx: Ctx) {
const r = express.Router();
r.get('/setup', handle(async () => ({
needed: await setupNeeded(ctx),
hubConnected: !!(await ctx.settings.get('hub_install_id')),
adminEmail: ctx.config.hubAdminEmail,
})));
r.post('/setup', limit(10, 60), handle(async (req) => {
if (!(await setupNeeded(ctx))) throw new ApiError(409, 'DONE', 'Accounts is already set up. Sign in instead.');
const b = req.body ?? {};
const fields: Record<string, string> = {};
const churchName = String(b.churchName ?? '').trim();
const name = String(b.name ?? '').trim();
const email = normaliseEmail(b.email);
if (churchName.length < 2) fields.churchName = 'Enter the church\'s name.';
if (name.length < 2) fields.name = 'Enter your name.';
const ep = emailProblem(email);
if (ep) fields.email = ep;
else if (ctx.config.hubAdminEmail && email !== normaliseEmail(ctx.config.hubAdminEmail)) fields.email = 'Use the email address your provider set up this site for.';
const pp = passwordProblem(b.password);
if (pp) fields.password = pp;
const hubConnected = !!(await ctx.settings.get('hub_install_id'));
if (!hubConnected && !String(b.licenceKey ?? '').trim()) fields.licenceKey = 'Enter the licence key from your provider (CCA-…).';
if (Object.keys(fields).length) throw new ApiError(400, 'VALIDATION', 'Some details need fixing.', fields);
if (!hubConnected) {
try {
await connectHub(ctx, String(b.licenceKey), { name, email });
} catch (e) {
const msg = (e as Error).message;
throw new ApiError(400, 'LICENCE', msg, { licenceKey: msg });
}
}
await updateProfile(ctx, { name: churchName });
const parts = name.split(/\s+/);
const notice = await currentNotice(ctx);
const a = await ctx.db.account.upsert({
where: { email },
create: { name, givenName: parts[0] ?? null, familyName: parts.slice(1).join(' ') || null, email, role: 'admin', passwordHash: await hashPassword(String(b.password)), noticeVersionAccepted: notice.version, newsAskedAt: ctx.now() },
update: { role: 'admin', status: 'active', passwordHash: await hashPassword(String(b.password)) },
});
await loginEvent(ctx, a.id, 'account_created', req);
await audit(ctx, { actorId: a.id, actorRole: 'admin', action: 'setup_completed', targetType: 'account', targetId: a.id, ip: clientIp(req) });
// Signing in sets up 2FA (admins must have it) and verifies the email address.
return { done: true, next: '/api/self/signin?returnTo=/admin' };
}));
return r;
}
@@ -0,0 +1,85 @@
// @crosscode/auth-client (the product side, packages/auth-client) against the real provider:
// what the Website, App and Events 3.0 will run.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { accountsClient, type AccountsClient } from '@crosscode/auth-client';
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
import { runDue } from '../src/links/deliveries.js';
import { signOutEverywhere } from '../src/oidc/sessions.js';
let h: Harness;
let auth: AccountsClient;
before(async () => {
h = await startHarness();
auth = await accountsClient({ accountsUrl: h.publicUrl, productUrl: h.productUrl, clientId: PRODUCT_ID, linkSecret: h.linkSecret, allowInsecure: true });
await h.makeAccount({ email: 'client@hope.test', password: 'Correct-horse-1' });
});
after(async () => { await h.close(); });
async function signInWith(returnTo: string) {
const browser = new Browser();
const { url, cookie } = await auth.startSignIn(returnTo);
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
const uid = signin.url.searchParams.get('uid')!;
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
return auth.finishSignIn(back.url, cookie);
}
describe('@crosscode/auth-client', () => {
test('signs in and returns to the page', async () => {
const r = await signInWith('/sermons/2026/advent?part=2');
assert.equal(r.claims.email, 'client@hope.test');
assert.equal(r.returnTo, '/sermons/2026/advent?part=2');
assert.ok(r.idToken);
});
test('a foreign return address is never followed', async () => {
for (const evil of ['//evil.example/x', 'https://evil.example/', '/\\evil.example']) {
assert.equal((await signInWith(evil)).returnTo, '/', evil);
}
});
test('without the cookie from starting, finishing fails', async () => {
await assert.rejects(auth.finishSignIn(`${h.productUrl}${OIDC_CLIENT_PATHS.callback}?code=x&state=y`, undefined), /expired/);
});
test('checks Accounts\' signed calls and refuses changed ones', async () => {
const { profileChanged } = await import('../src/accounts/service.js');
const a = (await h.db.account.findUnique({ where: { email: 'client@hope.test' } }))!;
h.received.length = 0;
await profileChanged(h.ctx, a.id as string);
await runDue(h.ctx);
const call = h.received.find((r) => r.path === '/api/accounts/v1/events')!;
const read = auth.verifyAccountsCall(call.body, call.headers as Record<string, string>);
assert.equal(read.type, 'user.updated');
assert.equal(read.sub, a.id);
assert.throws(() => auth.verifyAccountsCall(call.body.replace('client@hope.test', 'attacker@evil.test'), call.headers as Record<string, string>), /isn't signed/);
});
test('checks a back-channel logout token', async () => {
const browser = new Browser();
const { url, cookie } = await auth.startSignIn('/');
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
const step = await h.api(browser, 'POST', `/api/v2/interaction/${signin.url.searchParams.get('uid')}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
const { claims } = await auth.finishSignIn(back.url, cookie);
h.received.length = 0;
await signOutEverywhere(h.ctx, h.provider, claims.sub);
const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout)!;
const token = new URLSearchParams(logout.body).get('logout_token')!;
const out = await auth.verifyLogoutToken(token);
assert.equal(out.sub, claims.sub);
assert.ok(out.sid);
const [hd, p, s] = token.split('.');
const forged = `${hd}.${Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(p!, 'base64url').toString()), sub: 'someone-else' })).toString('base64url')}.${s}`;
await assert.rejects(auth.verifyLogoutToken(forged), /isn't valid/);
});
test('the sign-out address ends at the product', () => {
const u = new URL(auth.signOutUrl('id-token'));
assert.equal(u.pathname, '/api/oidc/session/end');
assert.equal(u.searchParams.get('post_logout_redirect_uri'), `${h.productUrl}/`);
});
});
+95
View File
@@ -0,0 +1,95 @@
// The small pieces: passwords (including bcrypt hashes Cross Events 3.0 will bring across), codes,
// recovery codes, secrets at rest, licence states, the church profile rules.
import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import bcrypt from 'bcryptjs';
import { hashPassword, needsRehash, passwordProblem, verifyPassword } from '../src/lib/passwords.js';
import { codeAt, generateSecret, matchStep, otpauthUrl } from '../src/lib/totp.js';
import { hashRecoveryCode, newRecoveryCodes, normaliseRecoveryCode } from '../src/lib/recoveryCodes.js';
import { Secrets } from '../src/lib/crypto.js';
import { stateFor, type LicenceClaims } from '../src/hub/licence.js';
import { normalisePhone } from '../src/accounts/service.js';
import { waNumber } from '../src/lib/messages.js';
describe('passwords', () => {
test('Argon2id hashes verify, wrong passwords don\'t', async () => {
const h = await hashPassword('Correct-horse-1');
assert.match(h, /^\$argon2id\$/);
assert.equal(await verifyPassword('Correct-horse-1', h), true);
assert.equal(await verifyPassword('wrong-password', h), false);
assert.equal(needsRehash(h), false);
});
test('bcrypt hashes from Cross Events verify and are marked for re-hashing', async () => {
const h = await bcrypt.hash('Old-events-password', 4);
assert.equal(await verifyPassword('Old-events-password', h), true);
assert.equal(needsRehash(h), true);
assert.equal(await verifyPassword('anything', null), false);
assert.equal(await verifyPassword('anything', 'not-a-hash'), false);
});
test('at least 8 characters', () => {
assert.ok(passwordProblem('short'));
assert.equal(passwordProblem('long-enough'), null);
});
});
describe('authenticator codes', () => {
test('a code works once, with a step either side for clock drift', () => {
const secret = generateSecret();
const now = Date.now();
const step = Math.floor(now / 30000);
assert.equal(matchStep(secret, codeAt(secret, step), { now }), step);
assert.equal(matchStep(secret, codeAt(secret, step - 1), { now }), step - 1);
assert.equal(matchStep(secret, codeAt(secret, step - 3), { now }), null);
assert.equal(matchStep(secret, codeAt(secret, step), { now, afterStep: step }), null);
assert.match(otpauthUrl(secret, 'a@b.co', 'Hope Family'), /^otpauth:\/\/totp\/Hope%20Family%3Aa%40b\.co\?secret=/);
});
test('the same codes as Cross Events 2.3 for the same secret (RFC 6238 test vector)', () => {
// RFC 6238 SHA-1 secret "12345678901234567890" in base32, T = 59 s → 94287082 (last 6 digits).
assert.equal(codeAt('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', 1), '287082');
});
});
describe('recovery codes', () => {
test('ten, readable, matched whatever the case and dashes', () => {
const { codes, hashes } = newRecoveryCodes();
assert.equal(codes.length, 10);
assert.match(codes[0]!, /^[a-z2-9]{4}-[a-z2-9]{4}-[a-z2-9]{4}$/);
assert.equal(hashRecoveryCode(codes[0]!.toUpperCase().replace(/-/g, ' ')), hashes[0]);
assert.equal(normaliseRecoveryCode('ABCD EFGH JKMN'), 'abcd-efgh-jkmn');
});
});
describe('secrets at rest', () => {
test('round trip; another key can\'t read it; changed data fails', () => {
const a = new Secrets('one-secret-that-is-long-enough-for-tests');
const enc = a.encrypt('totp-secret');
assert.match(enc, /^enc:/);
assert.equal(a.decrypt(enc), 'totp-secret');
assert.throws(() => new Secrets('another-secret-that-is-long-enough').decrypt(enc));
assert.throws(() => a.decrypt(`${enc.slice(0, -2)}00`));
});
});
describe('licence states (Accounts never goes read-only)', () => {
const base: LicenceClaims = { v: 1, installId: 'i', customer: 'Hope', status: 'active', licenceExpiresAt: null, validUntil: '2026-12-01T00:00:00Z', graceDays: 14 };
test('active, grace, lapsed, revoked, unlicensed', () => {
assert.equal(stateFor(base, 'i', new Date('2026-11-20')).state, 'active');
assert.equal(stateFor(base, 'i', new Date('2026-12-05')).state, 'grace');
assert.equal(stateFor(base, 'i', new Date('2027-01-01')).state, 'lapsed');
assert.equal(stateFor({ ...base, status: 'revoked' }, 'i').state, 'revoked');
assert.equal(stateFor(null, null).state, 'unlicensed');
assert.equal(stateFor(base, 'other').state, 'unlicensed');
});
});
describe('phone numbers', () => {
test('South African numbers in every common format', () => {
assert.equal(normalisePhone('082 123 4567'), '+27821234567');
assert.equal(normalisePhone('+27 82 123 4567'), '+27821234567');
assert.equal(normalisePhone('hello'), null);
assert.equal(waNumber('+27821234567'), '27821234567');
});
});
@@ -0,0 +1,210 @@
// Accounts and the church's products (docs/ACCOUNTS-1.0-PLAN.md §3–§7): signing out everywhere,
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
// church profile, Connect, and admin and setup rules.
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, test } from 'node:test';
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
import { Browser, PRODUCT_ID, ACCOUNTS_ID, startHarness, type Harness } from './support/harness.js';
import { runDue } from '../src/links/deliveries.js';
import { approveDeletion, runDeletionJob } from '../src/privacy/deletion.js';
import { finishIfComplete } from '../src/privacy/export.js';
import { codeAt } from '../src/lib/totp.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
beforeEach(() => { h.received.length = 0; for (const k of Object.keys(h.productReplies)) delete h.productReplies[k]; });
const isCallback = (u: URL) => u.pathname === OIDC_CLIENT_PATHS.callback;
/** Signs into Accounts' own pages (the account page). */
async function accountPage(email: string, password: string) {
const browser = new Browser();
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
const uid = url.searchParams.get('uid')!;
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
return { browser, uid, step };
}
describe('signing out everywhere', () => {
test('ends the session and tells each product it signed in to (back-channel logout)', async () => {
const a = await h.makeAccount({ email: 'out@hope.test', password: 'Correct-horse-1' });
const browser = new Browser();
await h.signIn(browser, 'out@hope.test', 'Correct-horse-1');
const res = await h.api(browser, 'POST', '/api/v2/me/sign-out-everywhere');
assert.equal(res.status, 200, JSON.stringify(res.body));
const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout);
assert.ok(logout, 'the product was told');
const token = new URLSearchParams(logout.body).get('logout_token')!;
const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString());
assert.equal(payload.sub, a.id);
assert.ok(payload.events['http://schemas.openid.net/event/backchannel-logout']);
// Signed out: the account page asks to sign in again.
assert.equal((await h.api(browser, 'GET', '/api/v2/me')).status, 401);
});
});
describe('back-channel calls', () => {
test('a profile change reaches the product as user.updated, signed with the link\'s secret', async () => {
await h.makeAccount({ email: 'thandi2@hope.test', password: 'Correct-horse-2' });
const page = await accountPage('thandi2@hope.test', 'Correct-horse-2');
assert.equal(page.step.body.stage, 'done', JSON.stringify(page.step.body));
await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account');
const put = await h.api(page.browser, 'PUT', '/api/v2/me', { name: 'Thandi Mokoena', phone: '082 123 4567' });
assert.equal(put.status, 200, JSON.stringify(put.body));
assert.equal(put.body.phone, '+27821234567');
await runDue(h.ctx);
const call = h.received.find((r) => r.path === '/api/accounts/v1/events');
assert.ok(call);
assert.ok(h.signedByLink(call), 'signed with the link secret');
const body = JSON.parse(call.body);
assert.equal(body.type, 'user.updated');
assert.equal(body.profile.name, 'Thandi Mokoena');
});
test('a product that can\'t be reached is tried again later, not lost', async () => {
const { queueCall } = await import('../src/links/deliveries.js');
const link = (await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } }))!;
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { url: 'http://127.0.0.1:9' } });
const [d] = await queueCall(h.ctx, 'church.changed', () => ({ schema: 'crosscode.church/1', type: 'church.changed' }));
await runDue(h.ctx);
const after1 = (await h.db.delivery.findUnique({ where: { id: d!.id } }))!;
assert.equal(after1.status, 'pending');
assert.equal(after1.attempts, 1);
assert.ok((after1.nextAttemptAt as Date) > new Date());
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { url: link.url } });
});
});
describe('deleting an account', () => {
test('deactivated at once; after approval each product is asked, "not yet" is asked again, then anonymised', async () => {
const a = await h.makeAccount({ email: 'leaving@hope.test', password: 'Correct-horse-3' });
const page = await accountPage('leaving@hope.test', 'Correct-horse-3');
await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account');
const del = await h.api(page.browser, 'POST', '/api/v2/me/delete', { password: 'Correct-horse-3' });
assert.equal(del.status, 200, JSON.stringify(del.body));
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.status, 'deactivated');
const req = (await h.db.deletionRequest.findFirst({ where: { accountId: a.id } }))!;
let answer: unknown = { schema: IDENTITY_SCHEMA, status: 'deferred', reason: 'Has a registration for Youth Camp (14 March)', retryAfter: new Date(Date.now() - 1000).toISOString() };
h.productReplies['user.deleted'] = () => answer;
await approveDeletion(h.ctx, req.id as string, { id: 'admin', role: 'admin' });
await runDue(h.ctx);
let state = (await h.db.deletionRequest.findUnique({ where: { id: req.id } }))!;
assert.equal(state.status, 'approved');
assert.equal((state.products as Record<string, { status: string }>)[PRODUCT_ID]!.status, 'deferred');
answer = { schema: IDENTITY_SCHEMA, status: 'deleted' };
await runDeletionJob(h.ctx);
await runDue(h.ctx);
state = (await h.db.deletionRequest.findUnique({ where: { id: req.id } }))!;
assert.equal(state.status, 'done');
const gone = (await h.db.account.findUnique({ where: { id: a.id } }))!;
assert.equal(gone.status, 'deleted');
assert.equal(gone.email, `deleted-${a.id}@deleted.invalid`);
assert.equal(gone.passwordHash, null);
});
});
describe('download my data', () => {
test('bundles Accounts\' part and the product\'s', async () => {
const a = await h.makeAccount({ email: 'mydata@hope.test', password: 'Correct-horse-4' });
h.productReplies['user.export'] = (body) => ({
schema: IDENTITY_SCHEMA, exportId: body.exportId, sub: a.id, product: 'website', generatedAt: new Date().toISOString(),
sections: [{ key: 'pages', title: 'Pages you edited', records: [{ title: 'Home' }] }],
});
const page = await accountPage('mydata@hope.test', 'Correct-horse-4');
await page.browser.follow(page.step.body.redirectTo as string, (u) => u.pathname === '/account');
const made = await h.api(page.browser, 'POST', '/api/v2/me/exports');
assert.equal(made.status, 200);
await runDue(h.ctx);
await finishIfComplete(h.ctx, made.body.id as string);
const list = await h.api(page.browser, 'GET', '/api/v2/me/exports');
assert.equal((list.body.items as { status: string }[])[0]!.status, 'ready');
const dl = await page.browser.request(`${h.publicUrl}/api/v2/me/exports/${made.body.id}/download`);
const file = await dl.json() as { parts: { product: string }[] };
assert.deepEqual(file.parts.map((p) => p.product).sort(), ['accounts', 'website']);
assert.ok(h.messenger.emails.some((e) => e.to === 'mydata@hope.test' && /ready/.test(e.subject)));
// Someone else can't download it.
assert.equal((await new Browser().request(`${h.publicUrl}/api/v2/me/exports/${made.body.id}/download`)).status, 401);
});
});
describe('the church profile', () => {
test('is served as crosscode.church/1 with the product links', async () => {
const res = await fetch(`${h.publicUrl}/api/church/v1`);
const body = (await res.json()) as { name: string; links: Record<string, string> };
assert.equal(churchSchema.safeParse(body).success, true, JSON.stringify(body));
assert.equal(body.name, 'Hope Family Church');
assert.equal(body.links.website, h.productUrl);
assert.equal(body.links.accounts, h.publicUrl);
});
});
describe('Connect from a product', () => {
test('a product the Hub listed connects and becomes a client; an unlisted one can\'t', async () => {
const appKey = generateEd25519();
const APP_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04';
await h.ctx.settings.set('hub_linked_products', JSON.stringify([{ product: 'app', installId: APP_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) }]));
const msg = (key = appKey) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'app', installId: APP_ID, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce() }, key.privateKeyPem);
const bad = await fetch(`${h.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(generateEd25519())) });
assert.equal(bad.status, 401);
const ok = await fetch(`${h.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg()) });
assert.equal(ok.status, 200);
assert.equal(((await ok.json()) as { type: string }).type, 'link.connected');
const client = await h.provider.Client.find(APP_ID);
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
});
});
describe('admin and setup', () => {
test('admin needs the admin role and a 2FA sign-in', async () => {
await h.makeAccount({ email: 'member@hope.test', password: 'Correct-horse-5' });
const member = await accountPage('member@hope.test', 'Correct-horse-5');
await member.browser.follow(member.step.body.redirectTo as string, (u) => u.pathname === '/account');
assert.equal((await h.api(member.browser, 'GET', '/api/v2/admin/people')).status, 403);
await h.makeAccount({ email: 'admin@hope.test', password: 'Correct-horse-6', role: 'admin' });
const admin = await accountPage('admin@hope.test', 'Correct-horse-6');
assert.equal(admin.step.body.stage, 'setup_two_factor', 'admins must have 2FA');
const setup = await h.api(admin.browser, 'POST', `/api/v2/interaction/${admin.uid}/two-factor/setup`, { method: 'totp' });
const done = await h.api(admin.browser, 'POST', `/api/v2/interaction/${admin.uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) });
await admin.browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account');
const people = await h.api(admin.browser, 'GET', '/api/v2/admin/people?q=member');
assert.equal(people.status, 200, JSON.stringify(people.body));
assert.deepEqual((people.body.items as { email: string }[]).map((p) => p.email), ['member@hope.test']);
// Viewing a person is access-logged.
const id = (people.body.items as { id: string }[])[0]!.id;
await h.api(admin.browser, 'GET', `/api/v2/admin/people/${id}`);
assert.equal(await h.db.accessLog.count({ where: { targetId: id } }), 1);
});
test('changes only from the site itself', async () => {
const res = await new Browser().request(`${h.publicUrl}/api/v2/password/forgot`, { body: { email: 'x@hope.test' }, origin: 'https://evil.example' });
assert.equal(res.status, 403);
});
test('setup only while there\'s no admin', async () => {
const res = await h.api(new Browser(), 'POST', '/api/v2/setup', { churchName: 'Other', name: 'Someone', email: 'someone@hope.test', password: 'Correct-horse-7' });
assert.equal(res.status, 409);
});
});
describe('the sign-out page', () => {
test('signing out from a product ends at that product\'s address', async () => {
const browser = new Browser();
const r = await h.signIn(browser, 'member@hope.test', 'Correct-horse-5');
assert.ok('tokens' in r);
const end = new URL(`${h.publicUrl}/api/oidc/session/end`);
end.search = new URLSearchParams({ id_token_hint: r.tokens.id_token!, post_logout_redirect_uri: `${h.productUrl}/` }).toString();
const page = await browser.request(end.toString());
const html = await page.text();
assert.match(html, /logout\.js/);
const xsrf = /name="xsrf" value="([^"]+)"/.exec(html)![1]!;
const confirm = await browser.request(`${h.publicUrl}/api/oidc/session/end/confirm`, { form: { xsrf, logout: 'yes' } });
const loc = confirm.headers.get('location') ?? '';
assert.equal(loc, `${h.productUrl}/`);
void isCallback;
});
});
+173
View File
@@ -0,0 +1,173 @@
// Signing in through Accounts end to end (docs/ACCOUNTS-1.0-PLAN.md §3–5, ROADMAP-v3 §9 release
// checks): a real oidc-provider, the real app, a test product on openid-client.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { identityClaimsSchema, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { Browser, startHarness, type Harness } from './support/harness.js';
import { codeAt } from '../src/lib/totp.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
const isCallback = (u: URL) => u.pathname === OIDC_CLIENT_PATHS.callback;
describe('signing in from a product', () => {
test('returns to the exact page, with crosscode.identity/1 claims', async () => {
await h.makeAccount({ email: 'thandi@hope.test', password: 'Correct-horse-1', phone: '+27821234567' });
const r = await h.signIn(new Browser(), 'thandi@hope.test', 'Correct-horse-1');
assert.ok('claims' in r, JSON.stringify(r));
assert.equal(r.returnTo, '/events/youth-camp?ticket=adult');
const claims = identityClaimsSchema.safeParse(r.claims);
assert.deepEqual(claims.error?.issues ?? [], []);
assert.equal(r.claims.email, 'thandi@hope.test');
assert.deepEqual(r.claims.amr, ['pwd']);
assert.equal(r.claims.two_factor, null);
});
test('a wrong password is refused without saying whether the account exists', async () => {
const browser = new Browser();
const started = await h.startSignIn('/');
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin');
const uid = url.searchParams.get('uid')!;
const wrong = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'thandi@hope.test', password: 'nope-nope-nope' });
const nobody = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'nobody@hope.test', password: 'nope-nope-nope' });
assert.equal(wrong.status, 401);
assert.deepEqual(wrong.body, nobody.body);
});
test('a second sign-in from the same browser goes straight back (one sign-in for every product)', async () => {
const browser = new Browser();
await h.signIn(browser, 'thandi@hope.test', 'Correct-horse-1');
const started = await h.startSignIn('/give');
const { url } = await browser.follow(started.url, (u) => isCallback(u) || u.pathname === '/signin');
assert.ok(isCallback(url), `expected the callback, got ${url}`);
const r = await h.finishSignIn(url, started);
assert.equal(r.returnTo, '/give');
});
});
describe('what the provider refuses', () => {
test('PKCE is required', async () => {
const started = await h.startSignIn('/');
const u = new URL(started.url);
u.searchParams.delete('code_challenge');
u.searchParams.delete('code_challenge_method');
const res = await new Browser().request(u.toString());
const loc = res.headers.get('location') ?? '';
assert.ok(res.status === 400 || /error=invalid_request/.test(loc), `status ${res.status} ${loc}`);
});
test('a redirect_uri that isn\'t the registered one is refused and never followed', async () => {
const started = await h.startSignIn('/');
const u = new URL(started.url);
u.searchParams.set('redirect_uri', 'https://evil.example/api/auth/callback');
const res = await new Browser().request(u.toString());
assert.equal(res.status, 400);
assert.equal(res.headers.get('location'), null);
});
test('an unknown client is refused', async () => {
const started = await h.startSignIn('/');
const u = new URL(started.url);
u.searchParams.set('client_id', '00000000-0000-4000-8000-00000000dead');
assert.equal((await new Browser().request(u.toString())).status, 400);
});
});
describe('two-factor', () => {
test('a product asking for 2FA (acr_values=mfa) gets it set up first, then amr says mfa', async () => {
await h.makeAccount({ email: 'sam@hope.test', password: 'Correct-horse-2', name: 'Sam Supervisor' });
const browser = new Browser();
const r = await h.signIn(browser, 'sam@hope.test', 'Correct-horse-2', '/dashboard', { acr_values: 'mfa' });
assert.ok('pending' in r);
assert.equal(r.pending.stage, 'setup_two_factor');
const setup = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor/setup`, { method: 'totp' });
const code = codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000));
const done = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor/setup/confirm`, { method: 'totp', code });
assert.equal(done.body.stage, 'done', JSON.stringify(done.body));
assert.equal((done.body.recoveryCodes as string[]).length, 10);
const back = await browser.follow(done.body.redirectTo as string, isCallback);
const signed = await h.finishSignIn(back.url, r.started);
assert.deepEqual(signed.claims.amr, ['pwd', 'otp', 'mfa']);
assert.equal(signed.claims.acr, 'mfa');
assert.equal(signed.returnTo, '/dashboard');
});
test('someone with 2FA by email enters the emailed code; a recovery code works instead', async () => {
const a = await h.makeAccount({ email: 'lerato@hope.test', password: 'Correct-horse-3', twoFactorMethod: 'email' });
const { replaceRecoveryCodes } = await import('../src/accounts/twoFactor.js');
const codes = await replaceRecoveryCodes(h.ctx, a.id as string);
const browser = new Browser();
const r = await h.signIn(browser, 'lerato@hope.test', 'Correct-horse-3');
assert.ok('pending' in r);
assert.equal(r.pending.stage, 'two_factor');
const wrong = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: '000000' });
assert.equal(wrong.status, 400);
const ok = await h.api(browser, 'POST', `/api/v2/interaction/${r.uid}/two-factor`, { code: h.messenger.lastCode('lerato@hope.test') });
assert.equal(ok.body.stage, 'done');
const b2 = new Browser();
const r2 = await h.signIn(b2, 'lerato@hope.test', 'Correct-horse-3');
assert.ok('pending' in r2);
const rec = await h.api(b2, 'POST', `/api/v2/interaction/${r2.uid}/two-factor`, { recoveryCode: codes[0]!.toUpperCase() });
assert.equal(rec.body.stage, 'done');
const again = await h.api(new Browser(), 'POST', `/api/v2/interaction/${r2.uid}/two-factor`, { recoveryCode: codes[0] });
assert.notEqual(again.status, 200);
});
});
describe('the steps in between still return to the page', () => {
test('sign-up: verify the email, then back to the product', async () => {
const browser = new Browser();
const started = await h.startSignIn('/events/camp/register?ticket=child');
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin');
const uid = url.searchParams.get('uid')!;
const signup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/signup`, { name: 'New Person', email: 'New@Hope.test', password: 'Correct-horse-4', acceptNotice: true, newsEmail: true });
assert.equal(signup.body.stage, 'verify_email', JSON.stringify(signup.body));
const verified = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/verify-email`, { code: h.messenger.lastCode('new@hope.test') });
assert.equal(verified.body.stage, 'done', JSON.stringify(verified.body));
const back = await browser.follow(verified.body.redirectTo as string, isCallback);
const r = await h.finishSignIn(back.url, started);
assert.equal(r.returnTo, '/events/camp/register?ticket=child');
assert.equal(r.claims.email_verified, true);
assert.deepEqual(r.claims.news_consent, { email: true, whatsapp: false });
});
test('a password reset in the middle carries on to the product', async () => {
await h.makeAccount({ email: 'forgot@hope.test', password: 'Old-password-1' });
const browser = new Browser();
const started = await h.startSignIn('/my-tickets');
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin');
const uid = url.searchParams.get('uid')!;
await h.api(browser, 'POST', '/api/v2/password/forgot', { email: 'forgot@hope.test', uid });
const link = new URL(h.messenger.lastLink('forgot@hope.test')!);
const reset = await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'New-password-1' });
assert.equal(reset.body.uid, uid);
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'forgot@hope.test', password: 'New-password-1' });
const back = await browser.follow(step.body.redirectTo as string, isCallback);
assert.equal((await h.finishSignIn(back.url, started)).returnTo, '/my-tickets');
// The link is single-use.
assert.equal((await h.api(browser, 'POST', '/api/v2/password/reset', { token: link.searchParams.get('token'), password: 'Other-password-1' })).status, 400);
});
test('a new privacy notice is accepted before going back, even when already signed in', async () => {
await h.makeAccount({ email: 'notice@hope.test', password: 'Correct-horse-5' });
const browser = new Browser();
await h.signIn(browser, 'notice@hope.test', 'Correct-horse-5');
const { publish } = await import('../src/privacy/notice.js');
const n = await publish(h.ctx, { title: 'Our new notice', body: 'x'.repeat(80) }, 'admin');
const started = await h.startSignIn('/after-notice');
const { url } = await browser.follow(started.url, (u) => isCallback(u) || u.pathname === '/signin');
assert.equal(url.pathname, '/signin');
const uid = url.searchParams.get('uid')!;
const view = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
assert.equal(view.body.stage, 'notice');
const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/notice`, { version: n.version });
const back = await browser.follow(done.body.redirectTo as string, isCallback);
const r = await h.finishSignIn(back.url, started);
assert.equal(r.returnTo, '/after-notice');
assert.equal(r.claims.privacy_notice_version, n.version);
});
});
@@ -0,0 +1,172 @@
/**
* The whole of Accounts on a real port with an in-memory database and messenger, plus a test
* product (an OIDC client built on openid-client, as the Website will be) that's linked and
* signs people in. Browser requests go through a small cookie jar, following redirects by hand.
*/
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import * as oidc from 'openid-client';
import { encodeState, decodeState, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, oidcClientSecret, verify } from '@crosscode/contracts/signing';
import { createApp } from '../../src/app.js';
import { createCtx, type Ctx } from '../../src/context.js';
import { loadConfig } from '../../src/lib/config.js';
import { MemoryMessenger } from '../../src/lib/messages.js';
import { hashPassword } from '../../src/lib/passwords.js';
import { createProvider } from '../../src/oidc/provider.js';
import { memoryDb, type MemoryDb } from './memoryDb.js';
export const ACCOUNTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
export const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
const listen = (server: http.Server) => new Promise<number>((resolve) => server.listen(0, '127.0.0.1', () => resolve((server.address() as AddressInfo).port)));
/** A browser: cookies per host, redirects followed by hand so each hop can be checked. */
export class Browser {
// Per host: name → value and the cookie's Path, sent only on paths under it (as browsers do;
// oidc-provider scopes its interaction cookie to the interaction's address).
private jar = new Map<string, Map<string, { value: string; path: string }>>();
private cookieHeader(url: URL) {
const c = this.jar.get(url.host);
if (!c) return '';
const under = (p: string) => url.pathname === p || url.pathname.startsWith(p.endsWith('/') ? p : `${p}/`) || p === '/';
return [...c].filter(([, v]) => under(v.path)).map(([k, v]) => `${k}=${v.value}`).join('; ');
}
private store(url: URL, res: Response) {
for (const line of res.headers.getSetCookie()) {
const [pair, ...attrs] = line.split(';');
const i = pair!.indexOf('=');
const name = pair!.slice(0, i).trim();
const value = pair!.slice(i + 1).trim();
const pathAttr = attrs.map((a) => a.trim()).find((a) => /^path=/i.test(a));
const path = pathAttr ? pathAttr.slice(5) : url.pathname.replace(/\/[^/]*$/, '') || '/';
if (!this.jar.has(url.host)) this.jar.set(url.host, new Map());
if (/expires=Thu, 01 Jan 1970/i.test(line) || /max-age=0/i.test(line) || value === '') this.jar.get(url.host)!.delete(name);
else this.jar.get(url.host)!.set(name, { value, path });
}
}
async request(url: string, init: { method?: string; body?: unknown; form?: Record<string, string>; origin?: string } = {}) {
const u = new URL(url);
const headers: Record<string, string> = { cookie: this.cookieHeader(u) };
let body: string | undefined;
if (init.body !== undefined) { headers['content-type'] = 'application/json'; body = JSON.stringify(init.body); }
if (init.form) { headers['content-type'] = 'application/x-www-form-urlencoded'; body = new URLSearchParams(init.form).toString(); }
if (init.origin) headers.origin = init.origin;
const res = await fetch(u, { method: init.method ?? (body ? 'POST' : 'GET'), headers, body, redirect: 'manual' });
this.store(u, res);
return res;
}
/** Follows redirects until a page that isn't one; returns every URL visited and the last response. */
async follow(url: string, stopAt?: (u: URL) => boolean) {
const visited: URL[] = [];
let current = new URL(url);
for (let i = 0; i < 10; i++) {
visited.push(current);
if (stopAt?.(current)) return { visited, res: null as Response | null, url: current };
const res = await this.request(current.toString());
const loc = res.headers.get('location');
if (res.status >= 300 && res.status < 400 && loc) {
current = new URL(loc, current);
continue;
}
return { visited, res, url: current };
}
throw new Error('Too many redirects');
}
}
export type Received = { path: string; headers: http.IncomingHttpHeaders; body: string };
export type Harness = Awaited<ReturnType<typeof startHarness>>;
export async function startHarness(opts: { now?: () => Date } = {}) {
// Accounts.
const server = http.createServer();
const port = await listen(server);
const publicUrl = `http://127.0.0.1:${port}`;
const config = { ...loadConfig({ ACCOUNTS_URL: publicUrl, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1' }) };
const db = memoryDb();
const messenger = new MemoryMessenger();
const ctx: Ctx = createCtx(config, db as never, { messenger, now: opts.now });
const provider = await createProvider(ctx);
server.on('request', createApp(ctx, provider));
await ctx.settings.setMany({ hub_install_id: ACCOUNTS_ID, church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope' }) });
// The test product: answers back-channel calls and logout, and is linked (so it's a client).
const received: Received[] = [];
const productReplies: Record<string, (body: Record<string, unknown>) => unknown> = {};
const productServer = http.createServer((req, res) => {
let body = '';
req.on('data', (c) => { body += c; });
req.on('end', () => {
received.push({ path: req.url ?? '', headers: req.headers, body });
const parsed = (() => { try { return JSON.parse(body); } catch { return {}; } })() as Record<string, unknown>;
const answer = productReplies[String(parsed.type ?? req.url)]?.(parsed) ?? { schema: IDENTITY_SCHEMA, ok: true };
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answer));
});
});
const productPort = await listen(productServer);
const productUrl = `http://127.0.0.1:${productPort}`;
const linkSecret = newLinkSecret();
const productKey = generateEd25519();
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: productUrl, publicKey: ed25519PublicToPem(productKey.publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
const issuer = new URL(`${publicUrl}/api/oidc`);
const client = await oidc.discovery(issuer, PRODUCT_ID, oidcClientSecret(linkSecret), undefined, { execute: [oidc.allowInsecureRequests] });
/** The product starts a sign-in from `returnTo`; returns the URL to send the browser to and what to check on return. */
async function startSignIn(returnTo: string, extra: Record<string, string> = {}) {
const verifier = oidc.randomPKCECodeVerifier();
const nonce = oidc.randomNonce();
const state = encodeState({ nonce, returnTo });
const url = oidc.buildAuthorizationUrl(client, {
redirect_uri: `${productUrl}${OIDC_CLIENT_PATHS.callback}`, scope: 'openid profile email phone crosscode', state, nonce,
code_challenge: await oidc.calculatePKCECodeChallenge(verifier), code_challenge_method: 'S256', ...extra,
});
return { url: url.toString(), verifier, nonce, state };
}
/** The product's callback: exchange the code; returns the claims and where it would send the person. */
async function finishSignIn(callbackUrl: URL, started: { verifier: string; nonce: string; state: string }) {
const tokens = await oidc.authorizationCodeGrant(client, callbackUrl, { pkceCodeVerifier: started.verifier, expectedState: started.state, expectedNonce: started.nonce, idTokenExpected: true });
const st = decodeState(callbackUrl.searchParams.get('state'));
return { claims: tokens.claims()!, tokens, returnTo: st?.returnTo ?? '/' };
}
/** Runs a whole sign-in for `email` / `password` and returns the claims. */
async function signIn(browser: Browser, email: string, password: string, returnTo = '/events/youth-camp?ticket=adult', extra: Record<string, string> = {}) {
const started = await startSignIn(returnTo, extra);
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin' || u.pathname === OIDC_CLIENT_PATHS.callback);
if (url.pathname === OIDC_CLIENT_PATHS.callback) return finishSignIn(url, started);
const uid = url.searchParams.get('uid')!;
const step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
if (step.body.stage !== 'done') return { pending: step.body, uid, started };
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
return finishSignIn(back.url, started);
}
async function api(browser: Browser, method: string, path: string, body?: unknown) {
const res = await browser.request(`${publicUrl}${path}`, { method, body, origin: publicUrl });
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
return { status: res.status, body: json };
}
async function makeAccount(data: Record<string, unknown> & { email: string; password?: string }) {
const { password, ...rest } = data;
return db.account.create({ data: { name: 'Thandi Test', emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash: await hashPassword(password ?? 'Correct-horse-1'), ...rest } });
}
/** Checks a back-channel call was signed with the link's secret. */
const signedByLink = (r: Received) => verify({ secret: linkSecret, timestamp: r.headers[LINK_HEADERS.timestamp], signature: r.headers[LINK_HEADERS.signature], rawBody: r.body }).ok;
async function close() {
await new Promise((r) => server.close(r));
await new Promise((r) => productServer.close(r));
}
return { ctx, db: db as MemoryDb, messenger, provider, publicUrl, productUrl, client, received, productReplies, linkSecret, productKey, startSignIn, finishSignIn, signIn, api, makeAccount, signedByLink, close };
}
@@ -0,0 +1,172 @@
/**
* An in-memory stand-in for the Prisma client: every model the app uses, with the schema's
* defaults and unique fields, and generic `where` matching (equality, in / notIn, gt / gte / lt /
* lte, not, contains with mode insensitive, AND / OR). Enough to run the whole app in tests,
* including oidc-provider's storage.
*/
import crypto from 'node:crypto';
type Row = Record<string, unknown>;
const DEFAULTS: Record<string, () => Row> = {
account: () => ({
givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active',
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0,
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null,
}),
recoveryCode: () => ({ usedAt: null }),
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
emailToken: () => ({ interactionUid: null, usedAt: null }),
loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }),
privacyNotice: () => ({ publishedById: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
productLink: () => ({ connectedById: null }),
oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }),
delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }),
dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }),
deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version' };
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
function matchValue(actual: unknown, cond: unknown): boolean {
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
const c = cond as Record<string, unknown>;
const insensitive = c.mode === 'insensitive';
return Object.entries(c).every(([op, x]) => {
switch (op) {
case 'mode': return true;
case 'equals': return v(actual) === v(x);
case 'in': return (x as unknown[]).map(v).includes(v(actual));
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
case 'not': return x === null ? actual != null : !matchValue(actual, x);
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
default: throw new Error(`memoryDb: no operator ${op}`);
}
});
}
return v(actual) === v(cond);
}
export function matches(row: Row, where: Row = {}): boolean {
return Object.entries(where ?? {}).every(([k, cond]) => {
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
if (k === 'NOT') return !matches(row, cond as Row);
return matchValue(row[k], cond);
});
}
const clone = <T>(x: T): T => structuredClone(x);
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
function order(rows: Row[], orderBy?: Row | Row[]) {
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
return [...rows].sort((a, b) => {
for (const o of list) {
const [k, dir] = Object.entries(o)[0]!;
const x = v(a[k]) as number;
const y = v(b[k]) as number;
const d = x < y ? -1 : x > y ? 1 : 0;
if (d) return dir === 'desc' ? -d : d;
}
return 0;
});
}
function prismaError(code: string, message: string) {
return Object.assign(new Error(message), { code });
}
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
const key = KEYS[name] ?? 'id';
const table = () => {
if (!tables.has(name)) tables.set(name, new Map());
return tables.get(name)!;
};
const findWhere = (where: Row) => {
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
return [...table().values()].find((r) => matches(r, where)) ?? null;
};
const checkUnique = (row: Row, except?: unknown) => {
for (const u of UNIQUE[name] ?? []) {
if (row[u] == null) continue;
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
}
};
const api = {
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
findFirst: async ({ where, orderBy }: { where?: Row; orderBy?: Row | Row[] } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? clone(r) : null; },
findMany: async ({ where, orderBy, take, skip, select }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row } = {}) =>
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => pick(clone(r), select)),
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
create: async ({ data }: { data: Row }) => {
const now = new Date();
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
checkUnique(row);
table().set(row[key], row);
return clone(row);
},
update: async ({ where, data }: { where: Row; data: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
checkUnique(next, r[key]);
table().set(r[key], next);
return clone(next);
},
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
let count = 0;
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
return { count };
},
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
const r = findWhere(where);
return r ? api.update({ where, data: update }) : api.create({ data: create });
},
delete: async ({ where }: { where: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
table().delete(r[key]);
cascade(name, r[key]);
return clone(r);
},
deleteMany: async ({ where }: { where?: Row } = {}) => {
let count = 0;
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
return { count };
},
};
const cascade = (from: string, id: unknown) => {
if (from === 'productLink') for (const [k, r] of tables.get('delivery') ?? []) if (r.linkId === id) tables.get('delivery')!.delete(k);
if (from === 'account') for (const t of ['recoveryCode', 'emailToken', 'loginEvent', 'noticeAcceptance', 'consentChange', 'dataExport', 'deletionRequest']) for (const [k, r] of tables.get(t) ?? []) if (r.accountId === id) tables.get(t)!.delete(k);
};
return api;
}
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRawUnsafe: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
export function memoryDb(): MemoryDb {
const tables = new Map<string, Map<unknown, Row>>();
const models = new Map<string, ReturnType<typeof model>>();
return new Proxy({} as MemoryDb, {
get(_t, prop: string) {
if (prop === 'tables') return tables;
if (prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
if (prop === '$disconnect') return async () => {};
if (prop === 'then') return undefined;
if (!models.has(prop)) models.set(prop, model(prop, tables));
return models.get(prop);
},
});
}
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
"include": ["src"]
}
+21
View File
@@ -0,0 +1,21 @@
{
// ES modules throughout (oidc-provider and openid-client are ESM only; docs/ACCOUNTS-1.0-PLAN.md §3).
"compilerOptions": {
"target": "ES2023",
"module": "nodenext",
"moduleResolution": "nodenext",
"lib": ["ES2023"],
"strict": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"rootDir": ".",
"outDir": "dist",
"types": ["node"]
},
"include": ["src", "tests", "scripts", "prisma.config.ts"]
}
+1
View File
@@ -0,0 +1 @@
test-results/
+4
View File
@@ -0,0 +1,4 @@
{
"private": true,
"type": "module"
}
+73
View File
@@ -0,0 +1,73 @@
/**
* The e2e backend (playwright.config.ts): Accounts on port 5210 with the in-memory database from the
* backend tests (no Postgres needed), and a test product on 5211 that signs people in through it
* with @crosscode/auth-client, as the Website will. The pages run with `next dev` on 3210 and send
* /api here.
*
* Test helpers on the product: GET /test/code?to=<email or phone> (the last code sent),
* GET /test/link?to=<email> (the last link sent), GET /test/totp?secret=… (the current app code).
*/
import http from 'node:http';
import { accountsClient } from '@crosscode/auth-client';
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
import { createApp } from '../backend/src/app.js';
import { createCtx } from '../backend/src/context.js';
import { loadConfig } from '../backend/src/lib/config.js';
import { MemoryMessenger } from '../backend/src/lib/messages.js';
import { hashPassword } from '../backend/src/lib/passwords.js';
import { codeAt } from '../backend/src/lib/totp.js';
import { createProvider } from '../backend/src/oidc/provider.js';
import { memoryDb } from '../backend/tests/support/memoryDb.js';
const WEB = 'http://localhost:3210';
const PRODUCT = 'http://localhost:5211';
const PRODUCT_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
const db = memoryDb();
const messenger = new MemoryMessenger();
// Behind Next's rewrite (as behind nginx in production): the public host comes in X-Forwarded-Host.
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
await ctx.settings.setMany({
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
});
const linkSecret = newLinkSecret();
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
const seed = (email: string, extra: Record<string, unknown> = {}) => hashPassword('Correct-horse-1').then((passwordHash) =>
db.account.create({ data: { name: 'Thandi Test', email, emailVerified: true, noticeVersionAccepted: 1, newsAskedAt: new Date(), passwordHash, ...extra } }));
await seed('thandi@hope.test');
await seed('admin@hope.test', { name: 'Ada Admin', role: 'admin' });
const provider = await createProvider(ctx);
http.createServer(createApp(ctx, provider)).listen(5210, '127.0.0.1', () => console.log('[e2e] Accounts on 5210'));
// ─── The test product ────────────────────────────────────────────────────────
// Made on the first sign-in: the pages (and so discovery through them) start after this server.
let authP: ReturnType<typeof accountsClient> | null = null;
const getAuth = () => (authP ??= accountsClient({ accountsUrl: WEB, productUrl: PRODUCT, clientId: PRODUCT_ID, linkSecret, allowInsecure: true }));
const cookieOf = (req: http.IncomingMessage, name: string) => String(req.headers.cookie ?? '').split(';').map((c) => c.trim().split('=')).find(([k]) => k === name)?.[1];
http.createServer(async (req, res) => {
const url = new URL(req.url ?? '/', PRODUCT);
const send = (status: number, body: string, type = 'text/html') => res.writeHead(status, { 'content-type': type }).end(body);
try {
if (url.pathname === '/start') {
const { url: to, cookie } = await (await getAuth()).startSignIn(url.searchParams.get('returnTo') ?? '/', { requireTwoFactor: url.searchParams.get('mfa') === '1' });
res.writeHead(302, { location: to, 'set-cookie': `signin=${cookie}; Path=/; HttpOnly; SameSite=Lax` }).end();
return;
}
if (url.pathname === '/api/auth/callback') {
const r = await (await getAuth()).finishSignIn(url, cookieOf(req, 'signin'));
send(200, `<!doctype html><title>Product</title><h1>Signed in to the product</h1><p id="email">${r.claims.email}</p><p id="return">${r.returnTo}</p><p id="amr">${r.claims.amr.join(' ')}</p>`);
return;
}
if (url.pathname === '/test/code') return send(200, messenger.lastCode(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
if (url.pathname === '/test/link') return send(200, messenger.lastLink(url.searchParams.get('to') ?? '') ?? '', 'text/plain');
if (url.pathname === '/test/totp') return send(200, codeAt(url.searchParams.get('secret') ?? '', Math.floor(Date.now() / 30000)), 'text/plain');
if (req.method === 'POST') return send(200, '{}', 'application/json');
send(200, '<!doctype html><title>Product home</title><h1>Product home</h1>');
} catch (e) {
send(500, `<pre>${String((e as Error).message)}</pre>`);
}
}).listen(5211, '127.0.0.1', () => console.log('[e2e] Test product on 5211'));
+103
View File
@@ -0,0 +1,103 @@
import { expect, test, type Page } from "@playwright/test";
// The release checks (ROADMAP-v3 §9) on Accounts' real pages: signing in from a deep link lands
// back on that page, through sign-up, a password reset and two-step sign-in set up on the way; a
// foreign return address is refused. A test product (e2e/server.ts) starts and finishes sign-ins.
const PRODUCT = "http://localhost:5211";
const helper = async (page: Page, path: string) => (await (await page.request.get(`${PRODUCT}${path}`)).text()).trim();
async function signIn(page: Page, email: string, password = "Correct-horse-1") {
await page.getByLabel("Email address").fill(email);
await page.getByLabel("Password").fill(password);
await page.getByRole("button", { name: "Sign in" }).click();
}
test("signing in from a deep link returns to that exact page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/events/youth-camp/register?ticket=adult")}`);
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
await signIn(page, "thandi@hope.test");
await expect(page.locator("#return")).toHaveText("/events/youth-camp/register?ticket=adult");
await expect(page.locator("#email")).toHaveText("thandi@hope.test");
});
test("a wrong password says so without saying whether the account exists", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/`);
await signIn(page, "thandi@hope.test", "not-the-password");
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
await signIn(page, "nobody@hope.test", "not-the-password");
await expect(page.locator("main").getByRole("alert")).toHaveText("That email address and password don't match.");
});
test("a foreign return address ends on the product's home page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("//evil.example/steal")}`);
await signIn(page, "thandi@hope.test");
await expect(page.locator("#return")).toHaveText("/");
});
test("sign-up with an emailed code, back to the page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=${encodeURIComponent("/give?fund=building")}`);
await page.getByRole("button", { name: "Create an account" }).click();
await page.getByLabel("Your name").fill("New Person");
await page.getByLabel("Email address").fill("new@hope.test");
await page.getByLabel("Password").fill("Correct-horse-2");
await page.getByLabel(/privacy notice/).check();
await page.getByRole("button", { name: "Create account" }).click();
await expect(page.getByRole("heading", { name: "Check your email" })).toBeVisible();
await page.getByLabel("Code").fill(await helper(page, "/test/code?to=new@hope.test"));
await page.getByRole("button", { name: "Continue" }).click();
await expect(page.locator("#return")).toHaveText("/give?fund=building");
await expect(page.locator("#email")).toHaveText("new@hope.test");
});
test("forgot password in the middle of signing in still returns to the page", async ({ page }) => {
await page.goto(`${PRODUCT}/start?returnTo=/my-tickets`);
await page.getByRole("link", { name: "Forgot your password?" }).click();
await page.getByLabel("Email address").fill("thandi@hope.test");
await page.getByRole("button", { name: "Send the link" }).click();
await expect(page.getByRole("status")).toContainText("a link is on its way");
await page.goto(await helper(page, "/test/link?to=thandi@hope.test"));
await page.getByLabel("New password").fill("Correct-horse-1");
await page.getByRole("button", { name: "Save and sign in" }).click();
await signIn(page, "thandi@hope.test");
await expect(page.locator("#return")).toHaveText("/my-tickets");
});
test("a product asking for two-step sign-in: set up with an app, recovery codes, then back", async ({ page }) => {
await page.goto(`${PRODUCT}/start?mfa=1&returnTo=/dashboard`);
await signIn(page, "thandi@hope.test");
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
await page.getByRole("button", { name: /An authenticator app/ }).click();
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`));
await page.getByRole("button", { name: "Turn on" }).click();
await expect(page.getByRole("heading", { name: "Save your recovery codes" })).toBeVisible();
await page.getByRole("button", { name: "I've saved them" }).click();
await expect(page.locator("#return")).toHaveText("/dashboard");
await expect(page.locator("#amr")).toHaveText("pwd otp mfa");
});
test("the account page: signs in first, 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 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");
});
test("admin: needs two-step sign-in, then lists people", async ({ page }) => {
await page.goto("/admin");
await signIn(page, "admin@hope.test");
await expect(page.getByRole("heading", { name: "Set up two-step sign-in" })).toBeVisible();
await expect(page.getByText("Admins must use a second step")).toBeVisible();
await page.getByRole("button", { name: /An authenticator app/ }).click();
const key = (await page.getByText(/Or type this key:/).innerText()).replace(/.*:\s*/, "").trim();
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.getByText("thandi@hope.test")).toBeVisible();
});
@@ -0,0 +1,22 @@
// PM2 config template. Each install keeps its own copy as ecosystem.config.cjs (not in git, so
// deploys never change it); crosscode creates it from this file the first time with the church's
// PM2 names and ports.
module.exports = {
apps: [
{
name: 'accounts-backend',
cwd: __dirname + '/backend',
script: 'dist/index.js',
env: { NODE_ENV: 'production' },
max_memory_restart: '400M',
},
{
name: 'accounts-frontend',
cwd: __dirname + '/frontend',
script: 'npm',
args: 'start -- -p 3200',
env: { NODE_ENV: 'production' },
max_memory_restart: '400M',
},
],
};
+24
View File
@@ -0,0 +1,24 @@
{
"schema": "crosscode.env-template/1",
"product": "accounts",
"files": {
"backend/.env": [
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
{ "name": "ACCOUNTS_SECRET", "layer": "generated", "required": true, "description": "Encrypts stored secrets (signing keys, 2FA secrets, link secrets) and signs cookies: never change it" },
{ "name": "ACCOUNTS_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address; the OIDC issuer is <this>/api/oidc" },
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg" },
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCA-…)" },
{ "name": "HUB_ADMIN_NAME", "layer": "install" },
{ "name": "HUB_ADMIN_EMAIL", "layer": "install", "description": "Setup only lets this address become the first admin" },
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
],
"frontend/.env.production": [
{ "name": "ACCOUNTS_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
]
}
}
+4
View File
@@ -0,0 +1,4 @@
node_modules/
.next/
next-env.d.ts
.env*
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
// Next.js 16's own flat configs, as Cross Events. Run with `npm run lint`.
export default defineConfig([
...nextVitals,
...nextTs,
{
rules: {
"react-hooks/exhaustive-deps": ["warn", { additionalHooks: "^useExternalEffect$" }],
// Logos and QR codes are small and come from the church's own settings.
"@next/next/no-img-element": "off",
},
},
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
]);
+25
View File
@@ -0,0 +1,25 @@
import type { NextConfig } from "next";
// Everything under /api is the backend (docs/ACCOUNTS-1.0-PLAN.md §1). On a server nginx sends it
// there; in development (and when Next is reached directly) this rewrite does.
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
const nextConfig: NextConfig = {
poweredByHeader: false,
transpilePackages: ["@crosscode/ui"],
async rewrites() {
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
},
async headers() {
return [{
source: "/:path*",
headers: [
{ key: "X-Robots-Tag", value: "noindex, nofollow" },
{ key: "Referrer-Policy", value: "same-origin" },
{ key: "X-Content-Type-Options", value: "nosniff" },
],
}];
},
};
export default nextConfig;
+35
View File
@@ -0,0 +1,35 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.0.0",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
"lucide-react": "^0.536.0",
"next": "^16.4.6",
"qrcode": "^1.5.4",
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"autoprefixer": "^10.4.21",
"eslint": "^10.13.0",
"eslint-config-next": "^16.4.6",
"postcss": "^8.5.6",
"tailwindcss": "3.4",
"typescript": "^5"
}
}
+1
View File
@@ -0,0 +1 @@
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
@@ -0,0 +1,269 @@
"use client";
import React, { useCallback, useState } from "react";
import QRCode from "qrcode";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Me = {
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
};
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
type Export = { id: string; status: string; createdAt: string; readyAt: string | null; expiresAt: string };
const METHOD = { totp: "an authenticator app", email: "a code by email", whatsapp: "a code on WhatsApp" } as const;
const EVENT: Record<string, string> = {
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
};
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() {
const branding = useBranding();
const [me, setMe] = useState<Me | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
const load = useCallback(async () => {
const r = await call<Me>("GET", "/me");
if (r.status === 401) return window.location.assign(selfSignIn("/account"));
if (r.ok) setMe(r.data);
}, []);
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>;
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>;
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>
{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} />
</div>
</Shell>
);
}
type Props = { me: Me; onDone: (t: string) => void; onFail: (t: string) => void };
function Profile({ me, onDone, onFail }: Props) {
const [busy, setBusy] = useState(false);
const [changingEmail, setChangingEmail] = useState(false);
return (
<Card>
<Heading>Your details</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
setBusy(true);
const r = await call("PUT", "/me", { name: f.get("name"), phone: f.get("phone") || null });
setBusy(false);
if (r.ok) onDone("Your details are saved, and the church's sites have them too.");
else onFail(r.error.message);
}}>
<Field label="Name" name="name" defaultValue={me.name} required autoComplete="name" />
<Field label="Mobile number" name="phone" type="tel" defaultValue={me.phone ?? ""} autoComplete="tel" />
<Button type="submit" busy={busy}>Save</Button>
</form>
<div className="mt-6 border-t pt-4">
<p className="text-sm text-gray-700">Email address: <strong>{me.email}</strong></p>
{!changingEmail ? (
<Button variant="link" className="mt-1 text-sm" onClick={() => setChangingEmail(true)}>Change it</Button>
) : (
<form className="mt-3" onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const r = await call("POST", "/me/email", { email: f.get("email"), password: f.get("password") });
if (r.ok) { setChangingEmail(false); onDone("Check your new email address for a link to confirm it. Until then you sign in with the old one."); } else onFail(r.error.message);
}}>
<Field label="New email address" name="email" type="email" required />
<Field label="Your password" name="password" type="password" required autoComplete="current-password" />
<Button type="submit">Send the link</Button>
</form>
)}
</div>
</Card>
);
}
function Security({ me, onDone, onFail }: Props) {
const [setup, setSetup] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string; qr?: string } | null>(null);
const [codes, setCodes] = useState<string[] | null>(null);
const start = async (method: string) => {
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", "/me/two-factor/setup", { method });
if (!r.ok) return onFail(r.error.message);
setSetup({ ...r.data, qr: r.data.otpauthUrl ? await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }) : undefined });
};
return (
<Card>
<Heading>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>}
</p>
{codes && (
<Notice tone="warning">
Save these recovery codes somewhere safe. Each works once; they won&apos;t be shown again.
<pre className="mt-2 font-mono">{codes.join("\n")}</pre>
</Notice>
)}
{setup ? (
<form onSubmit={async (e) => {
e.preventDefault();
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/two-factor/confirm", { method: setup.method, code: new FormData(e.currentTarget).get("code") });
if (!r.ok) return onFail(r.error.message);
setSetup(null);
setCodes(r.data.recoveryCodes);
onDone("Two-step sign-in is on.");
}}>
{setup.qr && <img src={setup.qr} alt="QR code for your authenticator app" className="mb-2 h-40 w-40" />}
{setup.secret && <p className="mb-3 break-all font-mono text-xs text-gray-600">Key: {setup.secret}</p>}
{setup.sentTo && <p className="mb-3 text-sm">We sent a code to <strong>{setup.sentTo}</strong>.</p>}
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required />
<div className="flex gap-2"><Button type="submit">Turn on</Button><Button type="button" variant="secondary" onClick={() => setSetup(null)}>Cancel</Button></div>
</form>
) : (
<div className="mb-4 flex flex-wrap gap-2">
<Button variant="secondary" onClick={() => start("totp")}>{me.twoFactor ? "Use an authenticator app" : "Turn on with an app"}</Button>
<Button variant="secondary" onClick={() => start("email")}>{me.twoFactor ? "Use email codes" : "Turn on with email"}</Button>
</div>
)}
{me.twoFactor && !setup && (
<PasswordAction label="New recovery codes" button="Make new codes" onSubmit={async (password) => {
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/recovery-codes", { password });
if (r.ok) { setCodes(r.data.recoveryCodes); onDone("New recovery codes made; the old ones no longer work."); } else onFail(r.error.message);
}} />
)}
{me.twoFactor && !setup && me.role !== "admin" && (
<PasswordAction label="Turn off two-step sign-in" button="Turn off" danger onSubmit={async (password) => {
const r = await call("POST", "/me/two-factor/off", { password });
if (r.ok) onDone("Two-step sign-in is off."); else onFail(r.error.message);
}} />
)}
<div className="mt-4 border-t pt-4">
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const r = await call("POST", "/me/password", { current: f.get("current"), password: f.get("password") });
if (r.ok) { e.currentTarget.reset(); onDone("Your password is changed."); } else onFail(r.error.message);
}}>
<Field label="Current password" name="current" type="password" autoComplete="current-password" required />
<Field label="New password" name="password" type="password" autoComplete="new-password" minLength={8} required />
<Button type="submit" variant="secondary">Change password</Button>
</form>
</div>
</Card>
);
}
function PasswordAction({ label, button, danger, onSubmit }: { label: string; button: string; danger?: boolean; onSubmit: (password: string) => void }) {
const [open, setOpen] = useState(false);
if (!open) return <p className="mb-2"><Button variant="link" className="text-sm" onClick={() => setOpen(true)}>{label}</Button></p>;
return (
<form className="mb-3 rounded-lg border p-3" onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("password"))); setOpen(false); }}>
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
<div className="flex gap-2"><Button type="submit" variant={danger ? "danger" : "primary"}>{button}</Button><Button type="button" variant="secondary" onClick={() => setOpen(false)}>Cancel</Button></div>
</form>
);
}
function Privacy({ me, onDone, onFail }: Props) {
const [exports, setExports] = useState<Export[]>([]);
const [confirmDelete, setConfirmDelete] = useState(false);
const loadExports = useCallback(async () => {
const r = await call<{ items: Export[] }>("GET", "/me/exports");
if (r.ok) setExports(r.data.items);
}, []);
useExternalEffect(() => { void loadExports(); }, [loadExports]);
return (
<Card>
<Heading>Privacy</Heading>
<form onChange={async (e) => {
const f = new FormData(e.currentTarget);
const r = await call("PUT", "/me/news", { email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" });
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
}}>
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
</form>
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
<div className="border-t pt-4">
<p className="mb-2 text-sm font-medium">Download my data</p>
<p className="mb-3 text-sm text-gray-600">Everything the church&apos;s sites hold about you, in one file. It takes a few minutes; we&apos;ll email you when it&apos;s ready.</p>
{exports.map((x) => (
<p key={x.id} className="mb-2 text-sm">
{when(x.createdAt)}: {x.status === "ready" ? <a className="text-brand underline" href={`/api/v2/me/exports/${x.id}/download`}>Download</a> : x.status === "collecting" ? "being put together…" : "expired"}
</p>
))}
<Button variant="secondary" onClick={async () => {
const r = await call("POST", "/me/exports");
if (r.ok) { onDone("We're putting your data together. We'll email you when it's ready."); void loadExports(); } else onFail(r.error.message);
}}>Ask for a copy</Button>
</div>
<div className="mt-4 border-t pt-4">
<p className="mb-2 text-sm font-medium">Delete my account</p>
{!confirmDelete ? (
<Button variant="link" className="text-sm text-red-700" onClick={() => setConfirmDelete(true)}>Delete my account…</Button>
) : (
<form onSubmit={async (e) => {
e.preventDefault();
const r = await call("POST", "/me/delete", { password: new FormData(e.currentTarget).get("password") });
// A full page load: the signed-out page has nothing of this session left.
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
if (r.ok) window.location.assign("/signed-out"); else onFail(r.error.message);
}}>
<Notice tone="warning">You&apos;ll be signed out of all the church&apos;s sites straight away. An admin then confirms the deletion, and each site removes what it holds about you (a site may wait until an event you&apos;re booked for is over).</Notice>
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
<div className="flex gap-2"><Button type="submit" variant="danger">Delete my account</Button><Button type="button" variant="secondary" onClick={() => setConfirmDelete(false)}>Cancel</Button></div>
</form>
)}
</div>
</Card>
);
}
function Activity({ onDone }: { onDone: (t: string) => void }) {
const [items, setItems] = useState<SignIn[]>([]);
useExternalEffect(() => {
let alive = true;
call<{ items: SignIn[] }>("GET", "/me/sign-ins").then((r) => { if (alive && r.ok) setItems(r.data.items); });
return () => { alive = false; };
}, []);
return (
<Card>
<Heading 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">
<span>{EVENT[e.type] ?? e.type}{e.site ? <span className="text-gray-500"> · {e.site.replace(/^https?:\/\//, "")}</span> : null}</span>
<span className="shrink-0 text-gray-500">{when(e.at)}</span>
</li>
))}
{!items.length && <li className="text-gray-500">Nothing yet.</li>}
</ul>
<Button variant="secondary" onClick={async () => {
const r = await call("POST", "/me/sign-out-everywhere");
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
if (r.ok) { onDone("You're signed out everywhere."); window.location.assign("/signed-out"); }
}}>Sign out everywhere</Button>
</Card>
);
}
@@ -0,0 +1,30 @@
"use client";
import { useState } from "react";
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
export function ConfirmEmail({ token }: { token: string }) {
const branding = useBranding();
const [state, setState] = useState<{ ok: boolean; text: string } | null>(null);
useExternalEffect(() => {
let alive = true;
call("POST", "/me/email/confirm", { token }).then((r) => {
if (!alive) return;
if (r.status === 401) return window.location.assign(selfSignIn(`/account/confirm-email?token=${encodeURIComponent(token)}`));
setState(r.ok ? { ok: true, text: "Your new email address is confirmed. Sign in with it from now on." } : { ok: false, text: r.error.message });
});
return () => { alive = false; };
}, [token]);
return (
<Shell branding={branding}>
<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>
</Card>
</Shell>
);
}
@@ -0,0 +1,8 @@
import { ConfirmEmail } from "./ConfirmEmail";
export const metadata = { title: "Confirm your email address" };
export default async function Page({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
const { token } = await searchParams;
return <ConfirmEmail token={token ?? ""} />;
}
@@ -0,0 +1,7 @@
import { Account } from "./Account";
export const metadata = { title: "Your account" };
export default function AccountPage() {
return <Account />;
}
@@ -0,0 +1,369 @@
"use client";
import React, { useCallback, useState } from "react";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
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");
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) => {
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"));
setAllowed(r.ok);
});
return () => { alive = false; };
}, []);
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>;
return (
<Shell branding={branding} wide aside={<a href="/account" className="text-sm text-brand underline">Your account</a>}>
<h1 className="mb-4 text-2xl font-semibold">Accounts admin</h1>
<nav className="mb-6 flex flex-wrap gap-2" aria-label="Admin sections">
{TABS.map(([id, label]) => (
<button key={id} type="button" onClick={() => { setTab(id); setMsg(null); }} aria-current={tab === id ? "page" : undefined}
className={`rounded-full px-3 py-1.5 text-sm ${tab === id ? "bg-brand text-white" : "border bg-white text-gray-700"}`}>{label}</button>
))}
</nav>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{tab === "people" && <People flash={flash} />}
{tab === "deletions" && <Deletions flash={flash} />}
{tab === "church" && <Church flash={flash} />}
{tab === "linked" && <Linked flash={flash} />}
{tab === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
{tab === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{tab === "notice" && <NoticeTab flash={flash} />}
{tab === "licence" && <Licence flash={flash} />}
{tab === "audit" && <Audit />}
</Shell>
);
}
// ─── People ──────────────────────────────────────────────────────────────────
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
function People({ flash }: { flash: Flash }) {
const [q, setQ] = useState("");
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
const [open, setOpen] = useState<PersonDetail | null>(null);
const search = useCallback(async (query: string) => {
const r = await call<{ items: Person[]; total: number }>("GET", `/admin/people?q=${encodeURIComponent(query)}`);
if (r.ok) setList(r.data);
}, []);
useExternalEffect(() => { void search(""); }, [search]);
const show = async (id: string) => {
const r = await call<PersonDetail>("GET", `/admin/people/${id}`);
if (r.ok) setOpen(r.data);
};
const act = async (path: string, body: unknown, ok: string) => {
const r = await call(path.endsWith("/role") || path.endsWith("/status") ? "PUT" : "POST", path, body);
if (r.ok) { flash("success", ok); if (open) void show(open.id); void search(q); } else flash("error", r.error.message);
};
return (
<div className="grid gap-6 md:grid-cols-2">
<Card>
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
<Button type="submit" variant="secondary">Search</Button>
</form>
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
<ul className="divide-y">
{list?.items.map((p) => (
<li key={p.id}>
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
<span className="block text-sm text-gray-500">{p.email}</span>
</button>
</li>
))}
</ul>
</Card>
{open && (
<Card>
<Heading sub={open.email}>{open.name}</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
<dt className="text-gray-500">Account since</dt><dd>{when(open.createdAt)}</dd>
<dt className="text-gray-500">Locked until</dt><dd>{when(open.lockedUntil)}</dd>
</dl>
<div className="mb-4 flex flex-wrap gap-2">
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
</div>
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
</Card>
)}
</div>
);
}
// ─── Deletions ───────────────────────────────────────────────────────────────
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
function Deletions({ flash }: { flash: Flash }) {
const [items, setItems] = useState<Deletion[]>([]);
const load = useCallback(async () => {
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
if (r.ok) setItems(r.data.items);
}, []);
useExternalEffect(() => { void load(); }, [load]);
return (
<Card>
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
<ul className="divide-y">
{items.map((d) => (
<li key={d.id} className="py-3">
<p className="font-medium">{d.person.name} <span className="text-sm font-normal text-gray-500">{d.person.email} · asked {when(d.requestedAt)}</span></p>
{d.status === "waiting_approval" ? (
<div className="mt-2 flex gap-2">
<Button variant="danger" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/approve`); if (r.ok) { flash("success", "Approved: each site is deleting what it holds."); void load(); } else flash("error", r.error.message); }}>Approve</Button>
<Button variant="secondary" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/cancel`); if (r.ok) { flash("success", "Cancelled; the account works again."); void load(); } else flash("error", r.error.message); }}>Cancel</Button>
</div>
) : (
<ul className="mt-2 text-sm text-gray-700">
{Object.entries(d.products).map(([id, s]) => <li key={id}>{s.product ?? id}: {s.status === "deferred" ? `waiting — ${s.reason} (asking again ${when(s.retryAfter)})` : s.status}</li>)}
</ul>
)}
</li>
))}
</ul>
</Card>
);
}
// ─── Church profile ──────────────────────────────────────────────────────────
type ChurchData = { name: string; shortName: string | null; branding: { logoUrl: string | null; colours: { primary: string; accent: string | null } }; contact: { email: string | null; phone: string | null; whatsapp: string | null } };
function Church({ flash }: { flash: Flash }) {
const [c, setC] = useState<ChurchData | null>(null);
const [fields, setFields] = useState<Record<string, string>>({});
useExternalEffect(() => {
let alive = true;
call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); });
return () => { alive = false; };
}, []);
if (!c) return <p className="text-gray-600">Loading…</p>;
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
return (
<Card>
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const r = await call<ChurchData>("PUT", "/admin/church", {
name: f.get("name"), shortName: nul(f.get("shortName")),
branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } },
contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) },
});
if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); }
}}>
<Field label="Name" name="name" defaultValue={c.name} required error={fields.name} />
<Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} />
<Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} />
<div className="grid grid-cols-2 gap-4">
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} />
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} />
</div>
<Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} />
<Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} />
<Field label="WhatsApp" name="whatsapp" defaultValue={c.contact.whatsapp ?? ""} error={fields["contact.whatsapp"]} />
<Button type="submit">Save</Button>
</form>
</Card>
);
}
// ─── Linked products ─────────────────────────────────────────────────────────
type LinkedItem = { installId: string; product: string; name: string; url: string; listed: boolean; connectedAt: string | null; signsInHere: boolean };
function Linked({ flash }: { flash: Flash }) {
const [data, setData] = useState<{ hubConnected: boolean; items: LinkedItem[] } | null>(null);
const load = useCallback(async () => {
const r = await call<{ hubConnected: boolean; items: LinkedItem[] }>("GET", "/admin/linked-products");
if (r.ok) setData(r.data);
}, []);
useExternalEffect(() => { void load(); }, [load]);
if (!data) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
{!data.hubConnected && <Notice tone="warning">Accounts isn&apos;t connected to the Hub yet (Licence).</Notice>}
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
<ul className="divide-y">
{data.items.map((l) => (
<li key={l.installId} className="flex flex-wrap items-center justify-between gap-2 py-3">
<span><span className="font-medium">{l.name}</span> <span className="text-sm text-gray-500">{l.url.replace(/^https?:\/\//, "")}</span><br />
<span className="text-sm text-gray-600">{l.signsInHere ? `Connected ${when(l.connectedAt)}` : "Not connected"}{!l.listed && " · no longer listed by the Hub"}</span></span>
{l.signsInHere
? <Button variant="secondary" onClick={async () => { if (!window.confirm(`Disconnect ${l.name}? People won't be able to sign in to it until it's connected again.`)) return; const r = await call("POST", `/admin/linked-products/${l.installId}/disconnect`); if (r.ok) { flash("success", "Disconnected."); void load(); } else flash("error", r.error.message); }}>Disconnect</Button>
: <Button disabled={!l.listed} onClick={async () => { const r = await call("POST", `/admin/linked-products/${l.installId}/connect`); if (r.ok) { flash("success", `Connected: ${l.name} signs people in here now.`); void load(); } else flash("error", r.error.message); }}>Connect</Button>}
</li>
))}
</ul>
</Card>
);
}
// ─── Settings ────────────────────────────────────────────────────────────────
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"],
session_days: ['Days "Keep me signed in" lasts', "number"],
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
};
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
useExternalEffect(() => {
let alive = true;
call<Record<string, string | boolean | null>>("GET", "/admin/settings").then((r) => { if (alive && r.ok) setValues(r.data); });
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 };
return (
<Card>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const body: Record<string, string> = {};
for (const k of keys) {
const kind = SETTING_LABELS[k]![1];
if (kind === "bool") body[k] = f.get(k) === "on" ? "true" : "false";
else body[k] = String(f.get(k) ?? "");
}
const r = await call("PUT", "/admin/settings", body);
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message);
}}>
{keys.map((k) => {
const [label, kind] = SETTING_LABELS[k]!;
const v = values[k];
if (kind === "bool") return <Checkbox key={k} name={k} label={label} defaultChecked={v === null ? defaults[k] ?? false : v === "true"} />;
if (kind === "secret") return <Field key={k} name={k} label={label} type="password" autoComplete="off" placeholder={v ? "Saved — leave empty to keep it" : ""} />;
return <Field key={k} name={k} label={label} type={kind === "number" ? "number" : "text"} defaultValue={typeof v === "string" ? v : ""} />;
})}
<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>}
</div>
</form>
</Card>
);
}
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
function NoticeTab({ flash }: { flash: Flash }) {
const [current, setCurrent] = useState<{ version: number; title: string; body: string } | null>(null);
const load = useCallback(async () => {
const r = await call<{ current: { version: number; title: string; body: string } }>("GET", "/admin/notices");
if (r.ok) setCurrent(r.data.current);
}, []);
useExternalEffect(() => { void load(); }, [load]);
if (!current) return <p className="text-gray-600">Loading…</p>;
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>
);
}
function Licence({ flash }: { flash: Flash }) {
const [s, setS] = useState<{ connected: boolean; state: string; customer: string | null; endsAt: string | null; lastHeartbeatAt: string | null; lastError: string | null } | null>(null);
const load = useCallback(async () => {
const r = await call<NonNullable<typeof s>>("GET", "/admin/licence");
if (r.ok) setS(r.data);
}, []);
useExternalEffect(() => { void load(); }, [load]);
if (!s) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
<dt className="text-gray-500">Customer</dt><dd>{s.customer ?? "—"}</dd>
<dt className="text-gray-500">Last heartbeat</dt><dd>{when(s.lastHeartbeatAt)}</dd>
</dl>
{s.lastError && <Notice tone="warning">{s.lastError}</Notice>}
{!s.connected && (
<form onSubmit={async (e) => {
e.preventDefault();
const r = await call("POST", "/admin/licence", { licenceKey: new FormData(e.currentTarget).get("licenceKey") });
if (r.ok) { flash("success", "Connected to the Hub."); void load(); } else flash("error", r.error.message);
}}>
<Field label="Licence key" name="licenceKey" placeholder="CCA-XXXX-XXXX-XXXX-XXXX" required />
<Button type="submit">Connect</Button>
</form>
)}
</Card>
);
}
function Audit() {
const [items, setItems] = useState<{ id: string; action: string; actorRole: string; targetType: string; targetId: string | null; createdAt: string }[]>([]);
useExternalEffect(() => {
let alive = true;
call<{ items: typeof items }>("GET", "/admin/audit").then((r) => { if (alive && r.ok) setItems(r.data.items); });
return () => { alive = false; };
}, []);
return (
<Card>
<Heading>Audit log</Heading>
<ul className="divide-y text-sm">
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
</ul>
</Card>
);
}
@@ -0,0 +1,7 @@
import { Admin } from "./Admin";
export const metadata = { title: "Admin" };
export default function AdminPage() {
return <Admin />;
}
@@ -0,0 +1,36 @@
"use client";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call } from "@/lib/api";
export function Forgot({ uid }: { uid: string | null }) {
const branding = useBranding();
const [sent, setSent] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<Card>
<Heading 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>
) : (
<form onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
const r = await call("POST", "/password/forgot", { email: new FormData(e.currentTarget).get("email"), uid: uid ?? undefined });
setBusy(false);
if (r.ok) setSent(true); else setError(r.error.message);
}}>
{error && <Notice tone="error">{error}</Notice>}
<Field label="Email address" name="email" type="email" autoComplete="email" required autoFocus />
<Button type="submit" busy={busy} className="w-full">Send the link</Button>
</form>
)}
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
</Card>
</Shell>
);
}
@@ -0,0 +1,8 @@
import { Forgot } from "./Forgot";
export const metadata = { title: "Forgot your password" };
export default async function Page({ searchParams }: { searchParams: Promise<{ uid?: string }> }) {
const { uid } = await searchParams;
return <Forgot uid={uid ?? null} />;
}
@@ -0,0 +1,13 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Defaults until the church profile's colour is set (layout.tsx overrides them per request). */
:root {
--brand: 31 78 121;
--brand-dark: 21 55 85;
}
body {
@apply bg-gray-50 text-gray-900 antialiased;
}
+29
View File
@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import "./globals.css";
import { BrandingProvider } from "@/components/BrandingProvider";
import { loadBranding, rgbVars } from "@/lib/branding";
export async function generateMetadata(): Promise<Metadata> {
const b = await loadBranding();
// Sign-in pages never belong in search results (ROADMAP-v3 §11).
return { title: { default: `Sign in · ${b.name}`, template: `%s · ${b.name}` }, robots: { index: false, follow: false } };
}
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const nonce = (await headers()).get("x-nonce") ?? undefined;
const b = await loadBranding();
const vars = rgbVars(b.colours.primary);
return (
<html lang="en-ZA">
<head>
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
</head>
<body>
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
{children}
</BrandingProvider>
</body>
</html>
);
}
+6
View File
@@ -0,0 +1,6 @@
import { redirect } from "next/navigation";
// Opening Accounts directly shows the account page (signing in first if needed).
export default function Home() {
redirect("/account");
}
@@ -0,0 +1,19 @@
import { Card, Heading, Shell } from "@crosscode/ui";
import { loadBranding } from "@/lib/branding";
export const metadata = { title: "Privacy notice" };
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
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;
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>
);
}
@@ -0,0 +1,32 @@
"use client";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
export function Reset({ token }: { token: string | null }) {
const branding = useBranding();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return (
<Shell branding={branding}>
<Card>
<Heading sub="At least 8 characters.">Choose a new password</Heading>
{error && <Notice tone="error">{error}</Notice>}
<form onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
const r = await call<{ uid: string | null }>("POST", "/password/reset", { token, password: new FormData(e.currentTarget).get("password") });
setBusy(false);
if (!r.ok) return setError(r.error.message);
// Back to the sign-in it started from (and on to that site), or to the account page.
window.location.assign(r.data.uid ? `/signin?uid=${encodeURIComponent(r.data.uid)}` : selfSignIn("/account"));
}}>
<Field label="New password" name="password" type="password" autoComplete="new-password" required minLength={8} autoFocus />
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
</form>
</Card>
</Shell>
);
}
@@ -0,0 +1,8 @@
import { Reset } from "./Reset";
export const metadata = { title: "Choose a new password" };
export default async function Page({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
const { token } = await searchParams;
return <Reset token={token ?? null} />;
}
+6
View File
@@ -0,0 +1,6 @@
import type { MetadataRoute } from "next";
// Accounts is never indexed (ROADMAP-v3 §11).
export default function robots(): MetadataRoute.Robots {
return { rules: [{ userAgent: "*", disallow: "/" }] };
}
@@ -0,0 +1,52 @@
"use client";
import React, { useState } from "react";
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, type ApiError } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type Status = { needed: boolean; hubConnected: boolean; adminEmail: string | null };
/** First run: the church's name, the first admin and the licence key (docs/ACCOUNTS-1.0-PLAN.md §8). */
export function Setup() {
const branding = useBranding();
const [status, setStatus] = useState<Status | null>(null);
const [error, setError] = useState<ApiError | null>(null);
const [busy, setBusy] = useState(false);
useExternalEffect(() => {
let alive = true;
call<Status>("GET", "/setup").then((r) => { if (alive && r.ok) setStatus(r.data); });
return () => { alive = false; };
}, []);
const f = (n: string) => error?.fields?.[n] ?? null;
return (
<Shell branding={branding}>
<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>
) : (
<form onSubmit={async (e) => {
e.preventDefault();
const d = new FormData(e.currentTarget);
setBusy(true);
setError(null);
const r = await call<{ next: string }>("POST", "/setup", { churchName: d.get("churchName"), name: d.get("name"), email: d.get("email"), password: d.get("password"), licenceKey: d.get("licenceKey") || undefined });
setBusy(false);
if (r.ok) window.location.assign(r.data.next); else setError(r.error);
}}>
{error && !error.fields && <Notice tone="error">{error.message}</Notice>}
<Field label="The church's name" name="churchName" required error={f("churchName")} />
<Field label="Your name" name="name" required autoComplete="name" error={f("name")} />
<Field label="Your email address" name="email" type="email" required autoComplete="email" defaultValue={status.adminEmail ?? ""} error={f("email")} />
<Field label="Password" name="password" type="password" required minLength={8} autoComplete="new-password" error={f("password")} hint="At least 8 characters. You'll also set up two-step sign-in." />
{!status.hubConnected && <Field label="Licence key" name="licenceKey" required placeholder="CCA-XXXX-XXXX-XXXX-XXXX" error={f("licenceKey")} hint="From your provider." />}
<Button type="submit" busy={busy} className="w-full">Set up and sign in</Button>
</form>
)}
</Card>
</Shell>
);
}
@@ -0,0 +1,7 @@
import { Setup } from "./Setup";
export const metadata = { title: "Set up Accounts" };
export default function SetupPage() {
return <Setup />;
}
@@ -0,0 +1,17 @@
"use client";
import { Card, Heading, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { selfSignIn } from "@/lib/api";
export default function SignedOutPage() {
const branding = useBranding();
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>
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
</Card>
</Shell>
);
}
@@ -0,0 +1,265 @@
"use client";
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 { call, type ApiError } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
type State = {
uid: string;
stage: "password" | "verify_email" | "two_factor" | "setup_two_factor" | "notice" | "news" | "done";
product: string;
signupEnabled: boolean;
loginHint?: string | null;
name?: string;
email?: string;
sentTo?: string;
method?: "totp" | "email" | "whatsapp";
methods?: string[];
why?: "admin" | "product";
notice?: { version: number; title: string; body: string };
updated?: boolean;
redirectTo?: string;
recoveryCodes?: string[];
};
/**
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). The backend says which step comes next;
* when it's done, the browser goes back to the product it came from.
*/
export function SignIn({ uid }: { uid: string }) {
const branding = useBranding();
const [state, setState] = useState<State | null>(null);
const [error, setError] = useState<ApiError | null>(null);
const [busy, setBusy] = useState(false);
const [mode, setMode] = useState<"signin" | "signup">("signin");
const [codes, setCodes] = useState<{ codes: string[]; next: string } | null>(null);
const apply = (s: State) => {
if (s.stage === "done" && s.redirectTo) {
if (s.recoveryCodes?.length) setCodes({ codes: s.recoveryCodes, next: s.redirectTo });
else window.location.assign(s.redirectTo);
return;
}
setState(s);
};
useExternalEffect(() => {
let alive = true;
call<State>("GET", `/interaction/${encodeURIComponent(uid)}/state`).then((r) => {
if (!alive) return;
if (r.ok) apply(r.data);
else setError(r.error);
});
return () => { alive = false; };
}, [uid]);
const submit = async (path: string, body: unknown) => {
setBusy(true);
setError(null);
const r = await call<State>("POST", `/interaction/${encodeURIComponent(uid)}${path}`, body);
setBusy(false);
if (r.ok) apply(r.data);
else setError(r.error);
return r;
};
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
if (codes) {
return frame(<RecoveryCodes codes={codes.codes} onDone={() => window.location.assign(codes.next)} />);
}
if (!state) {
return frame(error ? (
<>
<Heading>We couldn&apos;t continue</Heading>
<Notice tone="error">{error.message}</Notice>
</>
) : <p className="text-gray-600">Loading…</p>);
}
const err = error ? <Notice tone="error">{error.message}</Notice> : null;
const fieldError = (name: string) => error?.fields?.[name] ?? null;
switch (state.stage) {
case "password":
return frame(mode === "signin"
? <PasswordStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/password", b)} onSignUp={() => { setError(null); setMode("signup"); }} />
: <SignUpStep busy={busy} err={err} fieldError={fieldError} onSubmit={(b) => submit("/signup", b)} onBack={() => { setError(null); setMode("signin"); }} />);
case "verify_email":
return frame(<CodeStep title="Check your email" sub={<>We sent a 6-digit code to <strong>{state.sentTo}</strong>. Enter it to confirm your email address.</>} busy={busy} err={err} onSubmit={(code) => submit("/verify-email", { code })} onResend={() => submit("/resend", {})} />);
case "two_factor":
return frame(<TwoFactorStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/two-factor", b)} onResend={() => submit("/resend", {})} />);
case "setup_two_factor":
return frame(<SetupStep uid={uid} state={state} busy={busy} err={err} setError={setError} onConfirm={(b) => submit("/two-factor/setup/confirm", b)} />);
case "notice":
return frame(<NoticeStep state={state} busy={busy} err={err} onAccept={() => submit("/notice", { version: state.notice!.version })} />);
case "news":
return frame(<NewsStep busy={busy} err={err} onSubmit={(b) => submit("/news", b)} />);
default:
return frame(<p className="text-gray-600">Taking you back…</p>);
}
}
function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onSignUp: () => void }) {
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>
{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 />
<Checkbox name="remember" label="Keep me signed in on this device" defaultChecked />
<Button type="submit" busy={busy} className="w-full">Sign in</Button>
<div className="mt-4 flex flex-wrap justify-between gap-2 text-sm">
<a href={`/forgot?uid=${encodeURIComponent(state.uid)}`} className="text-brand underline">Forgot your password?</a>
{state.signupEnabled && <button type="button" onClick={onSignUp} className="text-brand underline">Create an account</button>}
</div>
</form>
);
}
function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean; err: React.ReactNode; fieldError: (n: string) => string | null; onSubmit: (b: object) => void; onBack: () => void }) {
const branding = useBranding();
const [phone, setPhone] = useState("");
return (
<form onSubmit={(e) => {
e.preventDefault();
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>
{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")} />
<Field label="Mobile number (optional)" name="phone" type="tel" autoComplete="tel" value={phone} onChange={(e) => setPhone(e.target.value)} error={fieldError("phone")} hint="For WhatsApp messages, if you'd like them." />
<Field label="Password" name="password" type="password" autoComplete="new-password" required minLength={8} error={fieldError("password")} hint="At least 8 characters." />
<Checkbox name="newsEmail" label="Send me church news by email" />
{phone && <Checkbox name="newsWhatsApp" label="Send me church news on WhatsApp" />}
<Checkbox name="acceptNotice" required label={<>I&apos;ve read the <a href="/privacy" target="_blank" className="text-brand underline">privacy notice</a></>} hint={fieldError("acceptNotice") ?? undefined} />
<Button type="submit" busy={busy} className="w-full">Create account</Button>
<p className="mt-4 text-sm"><button type="button" onClick={onBack} className="text-brand underline">I already have an account</button></p>
</form>
);
}
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>
{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>
{onResend && <p className="mt-4 text-sm"><button type="button" onClick={onResend} className="text-brand underline">Send a new code</button></p>}
</form>
);
}
function TwoFactorStep({ state, busy, err, onSubmit, onResend }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onResend: () => void }) {
const [recovery, setRecovery] = useState(false);
if (recovery) {
return (
<form onSubmit={(e) => { e.preventDefault(); onSubmit({ recoveryCode: new FormData(e.currentTarget).get("recoveryCode") }); }}>
<Heading sub="One of the recovery codes you saved when you turned on two-step sign-in. Each works once.">Use a recovery code</Heading>
{err}
<Field label="Recovery code" name="recoveryCode" autoComplete="off" required autoFocus />
<Button type="submit" busy={busy} className="w-full">Continue</Button>
<p className="mt-4 text-sm"><button type="button" onClick={() => setRecovery(false)} className="text-brand underline">Use a code instead</button></p>
</form>
);
}
const sub = state.method === "totp" ? "Enter the 6-digit code from your authenticator app." : <>We sent a 6-digit code to <strong>{state.sentTo}</strong>.</>;
return (
<>
<CodeStep title="Second step" sub={sub} busy={busy} err={err} onSubmit={(code) => onSubmit({ code })} onResend={state.method === "totp" ? undefined : onResend} />
<p className="mt-2 text-sm"><button type="button" onClick={() => setRecovery(true)} className="text-brand underline">Use a recovery code</button></p>
</>
);
}
function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string; state: State; busy: boolean; err: React.ReactNode; setError: (e: ApiError | null) => void; onConfirm: (b: object) => void }) {
const [started, setStarted] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string } | null>(null);
const [qr, setQr] = useState<string | null>(null);
const start = async (method: string) => {
setError(null);
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", `/interaction/${encodeURIComponent(uid)}/two-factor/setup`, { method });
if (!r.ok) return setError(r.error);
setStarted(r.data);
if (r.data.otpauthUrl) setQr(await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }));
};
const why = state.why === "admin" ? "Admins must use a second step when they sign in." : `${state.product} asks for a second step when you sign in.`;
if (!started) {
const labels: Record<string, [string, string]> = {
totp: ["An authenticator app", "Google Authenticator, Microsoft Authenticator, 1Password… Most secure, works without signal."],
email: ["A code by email", `Sent to ${state.email}.`],
whatsapp: ["A code on WhatsApp", "Sent to your mobile number."],
};
return (
<>
<Heading sub={why}>Set up two-step sign-in</Heading>
{err}
<div className="space-y-2">
{(state.methods ?? []).map((m) => (
<button key={m} type="button" onClick={() => start(m)} className="w-full rounded-lg border p-3 text-left hover:border-brand">
<span className="block font-medium">{labels[m]?.[0] ?? m}</span>
<span className="block text-sm text-gray-600">{labels[m]?.[1]}</span>
</button>
))}
</div>
</>
);
}
return (
<form onSubmit={(e) => { e.preventDefault(); onConfirm({ method: started.method, code: new FormData(e.currentTarget).get("code") }); }}>
<Heading sub={started.method === "totp" ? "Scan this with your authenticator app, then enter the code it shows." : <>We sent a code to <strong>{started.sentTo}</strong>.</>}>
{started.method === "totp" ? "Scan the QR code" : "Enter the code"}
</Heading>
{err}
{qr && <img src={qr} alt="QR code for your authenticator app" className="mx-auto mb-3 h-48 w-48" />}
{started.secret && <p className="mb-4 break-all text-center font-mono text-sm text-gray-600">Or type this key: {started.secret}</p>}
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required autoFocus />
<Button type="submit" busy={busy} className="w-full">Turn on</Button>
</form>
);
}
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>
<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>
<a className="rounded-lg border px-4 py-2.5 text-sm" download="recovery-codes.txt" href={`data:text/plain;charset=utf-8,${encodeURIComponent(text)}`}>Download</a>
</div>
<Button type="button" className="w-full" onClick={onDone}>I&apos;ve saved them</Button>
</>
);
}
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>
{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>
<Button type="button" busy={busy} className="w-full" onClick={onAccept}>I&apos;ve read it</Button>
</>
);
}
function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void }) {
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>
{err}
<Checkbox name="email" label="Yes, by email" />
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
<Button type="submit" busy={busy} className="w-full">Continue</Button>
</form>
);
}
@@ -0,0 +1,11 @@
import { redirect } from "next/navigation";
import { SignIn } from "./SignIn";
export const metadata = { title: "Sign in" };
// /signin?uid=… is a sign-in a product started; without one, sign in to the account page.
export default async function SignInPage({ searchParams }: { searchParams: Promise<{ uid?: string }> }) {
const { uid } = await searchParams;
if (!uid || !/^[A-Za-z0-9_-]{10,64}$/.test(uid)) redirect("/api/self/signin?returnTo=%2Faccount");
return <SignIn uid={uid} />;
}
@@ -0,0 +1,13 @@
"use client";
import React, { createContext, useContext } from "react";
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
export function BrandingProvider({ value, children }: { value: ClientBranding; children: React.ReactNode }) {
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}
export const useBranding = () => useContext(Ctx);
+26
View File
@@ -0,0 +1,26 @@
/**
* Calls to the backend from the browser (same address, under /api). Errors come back as
* { error: { code, message, fields? } }; `call` returns them instead of throwing.
*/
export type ApiError = { code: string; message: string; fields?: Record<string, string> };
export type ApiResult<T> = { ok: true; status: number; data: T } | { ok: false; status: number; error: ApiError };
export async function call<T = Record<string, unknown>>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: unknown): Promise<ApiResult<T>> {
let res: Response;
try {
res = await fetch(`/api/v2${path}`, {
method,
credentials: "same-origin",
headers: body !== undefined ? { "Content-Type": "application/json" } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
} catch {
return { ok: false, status: 0, error: { code: "OFFLINE", message: "We couldn't reach the server. Check your connection and try again." } };
}
const json = (await res.json().catch(() => ({}))) as { error?: ApiError };
if (!res.ok) return { ok: false, status: res.status, error: json.error ?? { code: "ERROR", message: "Something went wrong. Please try again." } };
return { ok: true, status: res.status, data: json as T };
}
/** Where to sign in to Accounts' own pages, coming back to `returnTo`. */
export const selfSignIn = (returnTo: string, extra = "") => `/api/self/signin?returnTo=${encodeURIComponent(returnTo)}${extra}`;
@@ -0,0 +1,30 @@
/** The church's branding from the backend, for the server-rendered frame of every page. */
export type BrandingData = {
name: string;
shortName: string | null;
logoUrl: string | null;
colours: { primary: string; accent: string | null };
signupEnabled: boolean;
setupNeeded: boolean;
};
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
export async function loadBranding(): Promise<BrandingData> {
try {
const res = await fetch(`${api}/api/v2/branding`, { cache: "no-store" });
if (res.ok) return (await res.json()) as BrandingData;
} catch {
// The backend is starting or down: plain defaults, the page still works.
}
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
}
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
export function rgbVars(hex: string): { brand: string; dark: string } {
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
const n = parseInt(m[1]!, 16);
const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
const d = (x: number) => Math.round(x * 0.8);
return { brand: `${r} ${g} ${b}`, dark: `${d(r)} ${d(g)} ${d(b)}` };
}
+14
View File
@@ -0,0 +1,14 @@
import { useEffect, type DependencyList } from "react";
/**
* `useEffect` for loading from the API and setting state from it (as Cross Events' lib/hooks.ts):
* the React Compiler lint can't tell that apart from state derived from other state.
*/
export function useExternalEffect(run: () => void | (() => void) | Promise<unknown>, deps: DependencyList) {
useEffect(() => {
const out = run();
return typeof out === "function" ? out : undefined;
// The caller's deps, checked at the call site by exhaustive-deps (additionalHooks).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse, type NextRequest } from "next/server";
/**
* A strict Content-Security-Policy with a fresh nonce per page (docs/ACCOUNTS-1.0-PLAN.md §10):
* no inline scripts or styles except Next's own and the church's colours, both carrying the nonce.
* Sign-in pages never load anything from another site.
*/
export function proxy(request: NextRequest) {
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const dev = process.env.NODE_ENV === "development";
const csp = [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev ? " 'unsafe-eval'" : ""}`,
`style-src 'self' 'nonce-${nonce}'`,
"img-src 'self' https: data:",
"font-src 'self'",
"connect-src 'self'",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
].join("; ");
const headers = new Headers(request.headers);
headers.set("x-nonce", nonce);
headers.set("Content-Security-Policy", csp);
const res = NextResponse.next({ request: { headers } });
res.headers.set("Content-Security-Policy", csp);
return res;
}
export const config = {
matcher: [{ source: "/((?!api|_next/static|_next/image|favicon.ico).*)", missing: [{ type: "header", key: "next-router-prefetch" }] }],
};
+13
View File
@@ -0,0 +1,13 @@
/** @type {import('tailwindcss').Config} */
// The church's colour is a CSS variable set per request in layout.tsx (from the church profile).
module.exports = {
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
theme: {
extend: {
colors: {
brand: { DEFAULT: "rgb(var(--brand) / <alpha-value>)", dark: "rgb(var(--brand-dark) / <alpha-value>)" },
},
},
},
plugins: [],
};
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
"exclude": ["node_modules"]
}
+34
View File
@@ -0,0 +1,34 @@
import { defineConfig, devices } from "@playwright/test";
// Accounts' pages end to end (docs/ACCOUNTS-1.0-PLAN.md §12): the real backend on an in-memory
// database with a test product (e2e/server.ts), and the Next.js pages. Run with `npm run test:e2e`
// in apps/accounts. Nothing needs a database.
export default defineConfig({
testDir: "./e2e",
testMatch: "**/*.spec.ts",
workers: 1,
fullyParallel: false,
timeout: 120_000,
expect: { timeout: 20_000 },
reporter: "list",
outputDir: "e2e/test-results",
use: { baseURL: "http://localhost:3210", trace: "retain-on-failure", navigationTimeout: 90_000 },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: [
{
command: "npx tsx e2e/server.ts",
url: "http://127.0.0.1:5210/api/health",
timeout: 120_000,
reuseExistingServer: false,
stdout: "pipe",
},
{
command: "npx next dev -p 3210",
cwd: "frontend",
url: "http://localhost:3210/privacy",
timeout: 180_000,
reuseExistingServer: false,
env: { ACCOUNTS_API_URL: "http://127.0.0.1:5210" },
},
],
});
+55
View File
@@ -0,0 +1,55 @@
# Cross Code server agent
Runs on every server (docs/AGENT-1.0-PLAN.md). It polls Cross Code Hub every 30 seconds for
signed jobs, runs the `crosscode` script for them, sends the results, and sends the server's
stats every 60 seconds. **It listens on nothing**: no port, no URL; every request goes out to the Hub.
## Joining a server
Hub → Servers → **Add server** shows a command with a one-time token (valid an hour):
```bash
curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
```
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
`crosscode-agent.service`.
## On the server
| What | Where |
|------|-------|
| Config (Hub address, server id, the Hub's pinned job key) | `/etc/crosscode/agent.json` |
| Private keys (never leave the server) | `/etc/crosscode/agent-ed25519.pem`, `agent-x25519.pem` |
| Seen job ids (90 days), unsent reports, exports in progress | `/var/lib/crosscode-agent/` |
| A job's opened config, only while it runs | `/run/crosscode-agent/` |
| Logs | `journalctl -u crosscode-agent` |
## Security
- **Jobs are signed** by the Hub's job key (Ed25519, pinned when joining). The agent refuses a
job that's unsigned, for another server, outside its time window, already seen, of an unknown
type, or with an argument outside its schema. Refusals are reported to the Hub.
- **Only the `crosscode` script runs**, with arguments built from the checked job (an array,
never a shell). There's no "run this command" job.
- **Config** (database admin, server settings) arrives sealed to this server's X25519 key. It's
opened into a root-only file for the job and removed straight after.
- **Log lines** sent with a report are filtered for passwords, tokens, keys and licence keys.
- **Exports** are encrypted on the server with a new key; the key travels in the job's report
so the Hub can email the download link, and the Hub doesn't store it.
## Updates
An `update-agent` job builds the new release next to the running one, switches `current`, and
restarts. If the new agent hasn't polled the Hub within 150 seconds, `revert.sh` switches back.
## Development
```bash
npm run build -w apps/agent # dist/cli.js: one file, everything bundled
npm test -w apps/agent # the no-listening-socket test runs on Linux, after a build
```
+23
View File
@@ -0,0 +1,23 @@
# The Cross Code server agent (docs/AGENT-1.0-PLAN.md §3). Root, because the crosscode script it
# runs needs root (PostgreSQL, PM2 for each app user, frpc). It listens on nothing.
[Unit]
Description=Cross Code server agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/node /opt/crosscode/agent/current/apps/agent/dist/cli.js run
Restart=always
RestartSec=10
RuntimeDirectory=crosscode-agent
RuntimeDirectoryMode=0700
StateDirectory=crosscode-agent
StateDirectoryMode=0700
Environment=NODE_ENV=production
# Logs: journalctl -u crosscode-agent
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target

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