diff --git a/CHANGELOG.md b/CHANGELOG.md index a963621..3112033 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## accounts@1.0.0, contracts@1.5.0 - unreleased + +Phase 3 (docs/ACCOUNTS-1.0-PLAN.md), partly built on `feat/accounts-1.0`. + +- **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` (deploy updates it when a + church has it; install doesn't yet). + ## events@2.4.0, contracts@1.4.0 - unreleased Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and diff --git a/apps/accounts/CHANGELOG.md b/apps/accounts/CHANGELOG.md new file mode 100644 index 0000000..78ed853 --- /dev/null +++ b/apps/accounts/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog — Accounts + +## [1.0.0] - unreleased + +The first release (docs/ACCOUNTS-1.0-PLAN.md). Not tagged yet: needs Hub 2.3.0, `crosscode +install`/`add` for Accounts, a Playwright run of the pages and the VM test first. + +### 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. diff --git a/apps/accounts/README.md b/apps/accounts/README.md index eb5ab53..f86d3b6 100644 --- a/apps/accounts/README.md +++ b/apps/accounts/README.md @@ -1,3 +1,20 @@ # 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.
`: 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. +- 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). diff --git a/apps/accounts/WHATS-NEW.md b/apps/accounts/WHATS-NEW.md new file mode 100644 index 0000000..11b3422 --- /dev/null +++ b/apps/accounts/WHATS-NEW.md @@ -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. diff --git a/apps/accounts/backend/scripts/export-church.ts b/apps/accounts/backend/scripts/export-church.ts new file mode 100644 index 0000000..f303ac7 --- /dev/null +++ b/apps/accounts/backend/scripts/export-church.ts @@ -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 + */ +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 '); + 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(); diff --git a/apps/accounts/backend/src/app.ts b/apps/accounts/backend/src/app.ts index 8f94147..0b7fbe8 100644 --- a/apps/accounts/backend/src/app.ts +++ b/apps/accounts/backend/src/app.ts @@ -19,6 +19,7 @@ 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(); @@ -35,7 +36,7 @@ export function createApp(ctx: Ctx, provider: Provider) { 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: process.env.npm_package_version || '1.0.0', db: h.db }); + 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) => { diff --git a/apps/accounts/backend/src/hub/client.ts b/apps/accounts/backend/src/hub/client.ts index d19f617..450181b 100644 --- a/apps/accounts/backend/src/hub/client.ts +++ b/apps/accounts/backend/src/hub/client.ts @@ -9,6 +9,7 @@ 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; @@ -41,9 +42,7 @@ async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: s return data; } -function version(): string { - return process.env.npm_package_version || '1.0.0'; -} +const version = appVersion; export async function health(ctx: Ctx) { let db = true; diff --git a/apps/accounts/backend/src/lib/version.ts b/apps/accounts/backend/src/lib/version.ts new file mode 100644 index 0000000..308e645 --- /dev/null +++ b/apps/accounts/backend/src/lib/version.ts @@ -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; +} diff --git a/apps/accounts/backend/tsconfig.json b/apps/accounts/backend/tsconfig.json index c4d0000..e099459 100644 --- a/apps/accounts/backend/tsconfig.json +++ b/apps/accounts/backend/tsconfig.json @@ -17,5 +17,5 @@ "outDir": "dist", "types": ["node"] }, - "include": ["src", "tests", "prisma.config.ts"] + "include": ["src", "tests", "scripts", "prisma.config.ts"] } diff --git a/apps/accounts/ecosystem.config.example.cjs b/apps/accounts/ecosystem.config.example.cjs new file mode 100644 index 0000000..ba2fdb4 --- /dev/null +++ b/apps/accounts/ecosystem.config.example.cjs @@ -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', + }, + ], +}; diff --git a/apps/accounts/env.template.json b/apps/accounts/env.template.json new file mode 100644 index 0000000..5d960e3 --- /dev/null +++ b/apps/accounts/env.template.json @@ -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 /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" } + ] + } +} diff --git a/docs/ACCOUNTS-1.0-PLAN.md b/docs/ACCOUNTS-1.0-PLAN.md index f0e6721..2429b6a 100644 --- a/docs/ACCOUNTS-1.0-PLAN.md +++ b/docs/ACCOUNTS-1.0-PLAN.md @@ -1,7 +1,10 @@ # Accounts 1.0.0 — one sign-in for every product of a church Phase **3** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§3, §8, §9; decisions 2, 14, 15, 17). Written -2026-11-18. **Decisions confirmed 2026-11-18** (all as proposed); building. +2026-11-18. **Decisions confirmed 2026-11-18** (all as proposed). **Partly built 2026-11-18** on +`feat/accounts-1.0` (not merged): the app, contracts 1.5.0, `packages/auth-client`, `packages/ui` and +the deploy hooks. Not yet: Hub 2.3.0, `crosscode install`/`add` for Accounts, the Playwright run and +the VM test. See [Changes while building](#changes-while-building). **What Accounts is:** a small OpenID Connect provider per church, at `accounts.`. People sign in there once and are signed in to all of the church's products. Members never see it @@ -43,8 +46,9 @@ notice versions) is supported from the start. 11. [What changes in each repo](#11-what-changes-in-each-repo) 12. [Testing](#12-testing) 13. [Releasing and rolling it out](#13-releasing-and-rolling-it-out) -14. [Decisions](#decisions) -15. [Still open](#still-open) +14. [Changes while building](#changes-while-building) +15. [Decisions](#decisions) +16. [Still open](#still-open) --- @@ -297,6 +301,26 @@ phone-first. 4. **Churches get Accounts with the Website** (phase 4) or with Events 3.0, whichever comes first for them (decision 6). Until then nothing uses it, so it isn't installed for its own sake. +## Changes while building + +1. **"Download my data" is one JSON file**, not a ZIP: every product's part as + `crosscode.identity/1` export sections, plus the products that didn't answer in 24 hours. +2. **The Accounts session is oidc-provider's own**, and the account page signs in like a product + (`accounts-self`, `/api/self/signin`), so there's one session to end everywhere. +3. **`church.changed`** is a hint at its own path (`/api/church/v1/changed`, contracts 1.5.0, + like `event.changed`), not a new `crosscode.identity/1` call type (that would need `/2`). + contracts 1.5.0 also exports `churchObjectSchema` (the profile without its cross-field checks). +4. **A product that's disconnected after a deletion was approved** doesn't hold it up. +5. **Tests run the whole app on a real port** with an in-memory database and messenger and a test + product on openid-client (`backend/tests/`, 37 tests): every sign-in path in §5, PKCE and + redirect refusals, 2FA set-up and recovery codes, back-channel logout, signed calls, deferred + deletion, export, Connect, admin rules. oidc-provider refuses private addresses for back-channel + logout; `LINKS_ALLOW_PRIVATE` (testing only) lets it reach 127.0.0.1. +6. **Accounts' part of a church export** is `accounts.json` (the church profile and people, no + secrets) next to the other products' files. +7. **`/api/health` reads the version from package.json** (PM2 doesn't set npm's variables), so + `crosscode deploy` can check it. + ## Decisions Confirmed by Joshua on 2026-11-18 (1, 4, 5 and 6 asked directly; the rest as proposed): diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index f617e1c..a339a41 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -29,7 +29,7 @@ for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)). | 1c | Cross Events 2.3.x: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). **`events@2.3.1`** 2026-11-18: Next.js 16.4.6 (security advisories for 16.2.0–16.4.4), so roll out 2.3.1, not 2.3.0. crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) | | 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 | | 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Built** 2026-11-18 ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md), decisions taken as proposed, "Changes while building" there): `feat/events-2.4` here, `feat/link-public-key` in events-hub, `feat/linked-products` in crosscode-site. Unit tests pass. **Not tagged:** the e2e spec and the VM test haven't run (no Postgres on the dev machine) | -| 3 | Accounts 1.0.0 (+ contracts 1.5.0, Hub 2.3.0) | **Planned** 2026-11-18: [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md), eight decisions to confirm before building | +| 3 | Accounts 1.0.0 (+ contracts 1.5.0, Hub 2.3.0) | **Partly built** 2026-11-18 on `feat/accounts-1.0` ([ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md), decisions confirmed): the app (backend, pages, 37 tests), contracts 1.5.0, `packages/auth-client`, `packages/ui`, deploy hooks. **Still to do:** Hub 2.3.0 (Accounts licence with the first product, New install with Accounts), `crosscode install`/`add` for Accounts, a Playwright run of the pages, the VM test, crosscode-site | | 4–7 | Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started | ## Next up diff --git a/package.json b/package.json index 71ee06f..973bedc 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "test:scripts": "bats scripts/tests", "typecheck": "npm run typecheck --workspaces --if-present", "lint": "eslint .", - "lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh scripts/lib/report.sh scripts/lib/env.sh scripts/lib/frpc.sh scripts/lib/manage.sh apps/agent/deploy/install.sh apps/agent/deploy/revert.sh", + "lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh scripts/products/accounts.sh scripts/lib/report.sh scripts/lib/env.sh scripts/lib/frpc.sh scripts/lib/manage.sh apps/agent/deploy/install.sh apps/agent/deploy/revert.sh", "check": "npm run lint && npm run lint:scripts && npm run typecheck && npm test && npm run test:scripts && npm run build" }, "engines": { diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index daca61e..cb5b2c3 100644 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -8,7 +8,7 @@ CROSSCODE_REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode # through it. PRODUCT_ORDER=(accounts events website app) # Products this version of the script can deploy (a products/.sh exists for each). -SUPPORTED_PRODUCTS=(events) +SUPPORTED_PRODUCTS=(accounts events) # Releases older than this get a warning; older than CROSSCODE_NODE_MIN the deploy is refused. CROSSCODE_NODE_MIN=20 CROSSCODE_NODE_WARN=22 diff --git a/scripts/products/accounts.env.template.json b/scripts/products/accounts.env.template.json new file mode 100644 index 0000000..5d960e3 --- /dev/null +++ b/scripts/products/accounts.env.template.json @@ -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 /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" } + ] + } +} diff --git a/scripts/products/accounts.sh b/scripts/products/accounts.sh new file mode 100644 index 0000000..a63dddc --- /dev/null +++ b/scripts/products/accounts.sh @@ -0,0 +1,132 @@ +# shellcheck shell=bash +# Accounts' hooks for the crosscode script (docs/ACCOUNTS-1.0-PLAN.md §9), the same hooks as +# products/events.sh. Every hook takes the product's checkout (ACCOUNTS_DIR, a checkout of +# crosscode-platform) and the app user. Values come from church.env (CENV): ACCOUNTS_DIR, +# ACCOUNTS_DOMAIN, ACCOUNTS_PM2 (" "), ACCOUNTS_PORTS (" "), +# ACCOUNTS_DB, ACCOUNTS_USER. + +accounts_app() { printf '%s/apps/accounts' "$1"; } + +accounts_pm2_names() { pvar accounts PM2; } + +accounts_api_port() { local p; read -r p _ <<< "$(pvar accounts PORTS)"; printf '%s' "${p:-5200}"; } +accounts_web_port() { local p; read -r _ p <<< "$(pvar accounts PORTS)"; printf '%s' "${p:-3200}"; } +accounts_health_url() { printf 'http://127.0.0.1:%s/api/health' "$(accounts_api_port)"; } + +accounts_expected_version() { + node -p 'require(process.argv[1]).version' "$(accounts_app "$1")/backend/package.json" +} + +# The shared packages Accounts is built with (contracts, auth-client for its tests, ui for its pages). +accounts_shared_packages() { + local p + for p in packages/contracts packages/ui packages/auth-client; do + [ -f "$1/$p/package.json" ] && printf '%s\n' "$p" + done +} + +# A database dump into backend/backups/ (the last 14 are kept), before every deploy and uninstall. +accounts_backup() { + local dir="$1" user="$2" backend + backend="$(accounts_app "$dir")/backend" + # shellcheck disable=SC2016 # the app user's shell expands these + run_as "$user" "$backend" bash -c ' + set -euo pipefail + url="$(grep -E "^DATABASE_URL=" .env | head -1 | cut -d= -f2- | sed -e "s/^\"//" -e "s/\"$//")" + mkdir -p backups + file="backups/accounts-$(date +%Y%m%d-%H%M%S).sql.gz" + pg_dump --no-owner --no-privileges "$url" | gzip > "$file" + chmod 600 "$file" + ls -1t backups/accounts-*.sql.gz | tail -n +15 | xargs -r rm -f + echo " $file"' +} + +accounts_install_deps() { + local -a ws=() + local p + while IFS= read -r p; do ws+=(-w "$p"); done < <(accounts_shared_packages "$1") + run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund --include-workspace-root "${ws[@]}" -w apps/accounts/backend -w apps/accounts/frontend +} + +accounts_migrate() { + run_as "$2" "$(accounts_app "$1")/backend" npm run prisma:deploy +} + +accounts_build() { + local p + for p in packages/contracts packages/auth-client; do + [ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1 + done + run_as "$2" "$(accounts_app "$1")/backend" npm run build && + run_as "$2" "$(accounts_app "$1")/frontend" npm run build +} + +accounts_rollback_build() { + accounts_install_deps "$1" "$2" && accounts_build "$1" "$2" +} + +# The install's own PM2 config (not in git), made from the example the first time. +accounts_ensure_pm2_config() { + local dir="$1" user="$2" app conf backend frontend + app="$(accounts_app "$dir")" + conf="$app/ecosystem.config.cjs" + [ -f "$conf" ] && return 0 + read -r backend frontend <<< "$(accounts_pm2_names)" + sed -e "s/'accounts-backend'/'${backend}'/" \ + -e "s/'accounts-frontend'/'${frontend}'/" \ + -e "s/-p 3200/-p $(accounts_web_port)/" \ + "$app/ecosystem.config.example.cjs" > "$conf" + chown "$user:$user" "$conf" 2>/dev/null || true + info "Created $conf from the example." +} + +accounts_reload() { + accounts_ensure_pm2_config "$1" "$2" + run_as "$2" "$(accounts_app "$1")" pm2 reload ecosystem.config.cjs --update-env +} + +# accounts.json (the church profile and the people, no secrets) into . +accounts_export() { + local app + app="$(accounts_app "$1")" + run_as "$2" "$app/backend" npx tsx scripts/export-church.ts --out-dir "$3" +} + +# Accounts has no uploads (the logo is an address). +accounts_copy_uploads() { mkdir -p "$2"; } + +# What uninstall keeps for 30 days: the backups and the .env (its ACCOUNTS_SECRET decrypts what's stored). +accounts_keep() { + local app dest="$2" + app="$(accounts_app "$1")" + mkdir -p "$dest" + [ ! -d "$app/backend/backups" ] || rsync -a "$app/backend/backups/" "$dest/backups/" + cp -p "$app/backend/.env" "$dest/backend.env" 2>/dev/null || true + chmod -R go-rwx "$dest" +} + +accounts_env_vars() { + printf '%s\n' --var "domain=$(pvar accounts DOMAIN)" --var "apiPort=$(accounts_api_port)" --var "webPort=$(accounts_web_port)" --var "church=$(cenv CHURCH)" +} + +# As events_resolve_failed_migrations: a migration that failed in this release and isn't in the +# previous one is marked as rolled back (the backup taken first has the database as it was). +accounts_resolve_failed_migrations() { + local dir="$1" user="$2" prev="$3" backend name + backend="$(accounts_app "$dir")/backend" + local -a failed + # shellcheck disable=SC2016 # SQL through psql, run as the app user + mapfile -t failed < <(run_as "$user" "$backend" bash -c ' + url="$(grep -E "^DATABASE_URL=" .env | head -1 | cut -d= -f2- | sed -e "s/^\"//" -e "s/\"$//")" + psql "$url" -At -c "select migration_name from _prisma_migrations where finished_at is null and rolled_back_at is null"') + for name in "${failed[@]}"; do + [ -n "$name" ] || continue + if git_in "$dir" cat-file -e "$prev:apps/accounts/backend/prisma/migrations/$name/migration.sql" 2>/dev/null; then + warn "accounts: $name failed but $prev has it too; left for a look (npx prisma migrate status)." + continue + fi + run_as "$user" "$backend" npx prisma migrate resolve --rolled-back "$name" >/dev/null + info "accounts: marked the failed migration $name as rolled back." + report_result "resolvedMigration" "$name" + done +}