Merge branch 'feat/accounts-1.9'

This commit is contained in:
2026-11-30 11:05:24 +02:00
46 changed files with 1516 additions and 53 deletions
+16
View File
@@ -2,6 +2,22 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## accounts@1.9.0 + @crosscode/demo 1.0.0 + crosscode script - 2026-11-30
Church App 1.0.0 groundwork in Accounts (docs/APP-1.0-PLAN.md §8 and §12). One migration. Details
in `apps/accounts/CHANGELOG.md`.
- **Accounts 1.9.0:** `messaging.get` and the `messaging.changed` hint (the App sends with the
church's one set of email and WhatsApp settings); the WhatsApp opt-out for every product
(`whatsapp.optout`, its own WAWP webhook for a church without Events, `whatsapp_opted_out` in
`user.updated`, "Turn WhatsApp back on" on the account page); a demo scenario's church profile,
logo, icon and people (`npm run demo -- --profile <scenario> --force`).
- **`@crosscode/demo` 1.0.0** (new, `packages/demo`, not tagged): the eight scenarios' churches,
people (same `sub` in every product) and SVG logos, for every product's demo loader.
- **crosscode script:** `crosscode demo <church> accounts --profile <scenario>` (backup, load,
reload); `--scenario <s>` on every demo (the profile must be the scenario's); Accounts installs
and builds `packages/demo`.
## contracts@1.21.0 - 2026-11-30 ## contracts@1.21.0 - 2026-11-30
Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the
+52
View File
@@ -1,5 +1,57 @@
# Changelog — Accounts # Changelog — Accounts
## [1.9.0] - 2026-11-30
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
`crosscode` script on `main` builds it). **One migration** (`20261130000000_accounts_1_9`): two
columns on `Account`, one on `ProductLink`, a `WhatsAppOptOut` table. No new .env variables. Part of
Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
### Added
- **`messaging.get`** (contracts 1.20.0): a linked product gets the church's email (SMTP) and
WhatsApp (WAWP) settings, the password and token sealed with the link's secret, and is
remembered (`ProductLink.messagingWantedAt`). The reply is never kept in `ProductRequest`.
- **`messaging.changed`**: when an admin changes the email or WhatsApp settings here, or a product
saves them (`messaging.set`), each product that asked is sent the hint at
`/api/accounts/v1/messaging-changed` (a `Delivery`, retried as the other calls), except the one
that made the change.
- **The WhatsApp opt-out for every product** (APP-1.0-PLAN decision 11):
- `whatsapp.optout` from a product that received a STOP: the number is kept (`WhatsAppOptOut`),
every account with it is opted out (`Account.whatsappOptedOut`), its news on WhatsApp turned
off (a consent change, `whatsapp_stop`), and `user.updated` goes to every product with
`whatsapp_opted_out: true`. A number without an account is kept too: an account that gets it
later (sign-up, the account page, `people.ensure`, `people.update`, an import) starts opted out.
- **Accounts' own WAWP webhook**, `POST /api/v2/webhooks/whatsapp?secret=…`, for a church without
Cross Events: a STOP (English or Afrikaans: STOP, STOPP, UNSUBSCRIBE, OPT OUT, UITTEKEN) opts
the number out and answers once with how to undo it. Admin → Email and WhatsApp → **WhatsApp
replies (STOP)** shows the address to give WAWP and when it last called (or that Cross Events
takes the replies).
- Accounts sends an opted-out person no WhatsApp: sign-in codes go by email, setting WhatsApp up
as the two-step method is refused, sign-in notices skip it.
- **Turn WhatsApp back on** on the account page (Privacy), `POST /api/v2/me/whatsapp-on`: the
number's STOP is forgotten and the products are told. News on WhatsApp stays off until ticked.
- "Download my data" shows whether WhatsApp is off and since when.
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12), for demo sites only:
- `npm run demo -- --profile <scenario> --force` (`--list` for the eight), run by
`crosscode demo <church> accounts --profile <scenario>` after a backup. The church profile
becomes the scenario's church (name, short name, locale, colours, font pairing, corners,
campuses, service times, contact, social links), and `church.changed` goes to the products.
- Its **logo and icon**, drawn for the demo (`@crosscode/demo`), at
`/api/demo-assets/<scenario>/logo.svg` and `icon.svg`.
- Its **people** (54 to about 2 450, enough for the scenario's App band), at example.com with the
password `Demo@1234`, each with the same account id on every load and in every product
(`demoId`). Demo people from another scenario are anonymised; real people (any other address)
and Accounts admins are never touched; loading a scenario again brings its people back with
their ids.
### Checked on PostgreSQL 18
All three migrations on an empty database (the result matches the schema exactly); scenario loads
(Acacia Hill 0.8 s, Riverside's 2 457 people 3.4 s, switching back 14.7 s), the people's ids kept,
a real person untouched; the STOP opt-out, a known number on a new account, turning it back on;
`messaging.changed` queued; `npm run demo` with and without `--force`.
## [1.8.0] - 2026-11-26 ## [1.8.0] - 2026-11-26
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
+11
View File
@@ -3,6 +3,17 @@
What each version changes for the church, in plain language (read by the Hub like Cross Events' 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). WHATS-NEW.md; a section shows once its version is tagged).
## 1.9.0
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
WhatsApp from any of your church's sites any more, reminders and sign-in codes included (codes
come by email instead). They can turn WhatsApp back on from their account page. Without Cross
Events, Admin → Email and WhatsApp shows the address to give WAWP, so the replies reach Accounts.
- Getting ready for the **Church App**: it will send with the email and WhatsApp settings you
already have, without asking for its own, and pick up any change you make here.
- **Demo churches** for Cross Code's demo sites: a church's name, logo, colours, service times and
people for each of eight demo scenarios. Never used on a real church's sign-in.
## 1.8.0 ## 1.8.0
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that - **An easier admin.** Admin opens on an overview: how many people have an account, anything that
+4 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/accounts-backend", "name": "@crosscode/accounts-backend",
"version": "1.8.0", "version": "1.9.0",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API", "description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true, "private": true,
"type": "module", "type": "module",
@@ -14,10 +14,12 @@
"postinstall": "prisma generate", "postinstall": "prisma generate",
"prisma:generate": "prisma generate", "prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate", "prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status" "prisma:status": "prisma migrate status",
"demo": "tsx scripts/demo.ts"
}, },
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/demo": "*",
"@node-rs/argon2": "^2.2.2", "@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1", "@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1", "@prisma/client": "^7.10.1",
@@ -0,0 +1,20 @@
-- Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the WhatsApp opt-out for every product, and the
-- products that asked for the church's email and WhatsApp settings (messaging.get).
-- AlterTable
ALTER TABLE "Account" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "whatsappOptedOutAt" TIMESTAMP(3);
-- AlterTable
ALTER TABLE "ProductLink" ADD COLUMN "messagingWantedAt" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "WhatsAppOptOut" (
"phone" TEXT NOT NULL,
"keyword" TEXT NOT NULL,
"source" TEXT NOT NULL,
"receivedAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "WhatsAppOptOut_pkey" PRIMARY KEY ("phone")
);
+30 -13
View File
@@ -58,6 +58,10 @@ model Account {
// 1.1.0: moved in from a product with 2FA but without recovery codes (Events keys its codes with // 1.1.0: moved in from a product with 2FA but without recovery codes (Events keys its codes with
// its own secret, so they can't move): new ones are shown after the next sign-in's second step. // its own secret, so they can't move): new ones are shown after the next sign-in's second step.
recoveryCodesNeeded Boolean @default(false) recoveryCodesNeeded Boolean @default(false)
// 1.9.0: replied STOP to the church's WhatsApp number (APP-1.0-PLAN §8): no product sends them
// WhatsApp until they turn it back on here. Sent to products as `whatsapp_opted_out`.
whatsappOptedOut Boolean @default(false)
whatsappOptedOutAt DateTime?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -201,20 +205,23 @@ model AppSetting {
// A linked product (Connect, crosscode.link/1). Each is also an OIDC client (§4): client_id is // 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`. // installId, the client secret is derived from `secret`, the addresses are fixed paths on `url`.
model ProductLink { model ProductLink {
installId String @id installId String @id
product String // events | website | app product String // events | website | app
url String url String
publicKey String publicKey String
secret String // encrypted secret String // encrypted
connectedAt DateTime connectedAt DateTime
connectedById String? connectedById String?
// 1.1.0: a move of this product's users into Accounts is under way (import.begin … finish). // 1.1.0: a move of this product's users into Accounts is under way (import.begin … finish).
importStartedAt DateTime? importStartedAt DateTime?
createdAt DateTime @default(now()) // 1.9.0: asked for the church's email and WhatsApp settings (messaging.get), so it's sent
updatedAt DateTime @updatedAt // messaging.changed when they change.
deliveries Delivery[] messagingWantedAt DateTime?
people ProductPerson[] createdAt DateTime @default(now())
requests ProductRequest[] updatedAt DateTime @updatedAt
deliveries Delivery[]
people ProductPerson[]
requests ProductRequest[]
} }
// 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it). // 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it).
@@ -244,6 +251,16 @@ model ProductRequest {
@@index([createdAt]) @@index([createdAt])
} }
// 1.9.0: numbers that replied STOP (APP-1.0-PLAN §8), kept with or without an account, so an
// account that gets the number later starts opted out. Removed when the person turns WhatsApp on.
model WhatsAppOptOut {
phone String @id // E.164
keyword String
source String // the product that received it, or "accounts" (its own webhook)
receivedAt DateTime
createdAt DateTime @default(now())
}
model LinkNonce { model LinkNonce {
nonce String @id nonce String @id
seenAt DateTime @default(now()) seenAt DateTime @default(now())
+50
View File
@@ -0,0 +1,50 @@
/**
* Loads a demo scenario's church and people into Accounts (1.9.0, docs/APP-1.0-PLAN.md §12).
*
* npm run demo -- --profile <scenario> [--scenario <scenario>] --force
* npm run demo -- --list
*
* It replaces the church profile and the demo people, so it needs --force. On a server,
* `crosscode demo <church> accounts --profile …` runs it (backup first), for the Hub's demo sites;
* Accounts loads first in a scenario, then Cross Events, the Website and the App.
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
import { agent } from '@crosscode/contracts';
import { PrismaClient } from '../src/generated/prisma/client.js';
import { createCtx } from '../src/context.js';
import { loadConfig } from '../src/lib/config.js';
import { loadScenario } from '../src/demo/scenario.js';
const arg = (name: string) => {
const i = process.argv.indexOf(`--${name}`);
return i > 0 ? process.argv[i + 1] : undefined;
};
if (process.argv.includes('--list')) {
for (const s of agent.DEMO_SCENARIOS) console.log(`${s.key.padEnd(18)} ${s.label}`);
process.exit(0);
}
const profile = agent.demoScenarioSchema.safeParse(arg('profile'));
if (!profile.success) {
console.error(`Usage: npm run demo -- --profile <scenario> --force (one of ${agent.DEMO_SCENARIO_KEYS.join(', ')}; --list)`);
process.exit(2);
}
const scenario = arg('scenario');
if (scenario !== undefined && scenario !== profile.data) {
console.error(`--scenario ${scenario} loads ${agent.demoScenario(agent.demoScenarioSchema.parse(scenario)).profiles.accounts} in Accounts, not ${profile.data}.`);
process.exit(2);
}
if (!process.argv.includes('--force')) {
console.error('This replaces the church profile and the demo people. Add --force to do it (demo sites only).');
process.exit(1);
}
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
const ctx = createCtx(loadConfig(), db);
try {
const r = await loadScenario(ctx, profile.data);
console.log(`${r.church} loaded: ${r.people} people (${r.created} new, ${r.updated} brought back, ${r.removed} from before removed). The linked products are told the church changed.`);
} finally {
await db.$disconnect();
}
@@ -44,6 +44,8 @@ export function profileOf(a: Account): Profile {
phone_number: a.phone, phone_number: a.phone,
phone_number_verified: a.phoneVerified, phone_number_verified: a.phoneVerified,
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
// 1.9.0 (contracts 1.20.0): replied STOP; no product sends them WhatsApp.
whatsapp_opted_out: a.whatsappOptedOut,
}; };
} }
@@ -112,7 +114,11 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church'; 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 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.`; 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' && a.phone) { // 1.9.0: someone who replied STOP gets no WhatsApp, codes included: email instead.
if (method === 'whatsapp' && a.phone && a.whatsappOptedOut && purpose !== 'sign_in') {
throw new SendError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page, or choose another way to get your codes.', 'CODE_NOT_SENT');
}
if (method === 'whatsapp' && a.phone && !a.whatsappOptedOut) {
try { try {
await ctx.messenger.whatsapp({ to: a.phone, text }); await ctx.messenger.whatsapp({ to: a.phone, text });
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') }; return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
@@ -47,7 +47,7 @@ export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: str
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' }); const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site }); const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html }); await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) { if (a.phone && a.phoneVerified && !a.whatsappOptedOut && (await ctx.messenger.whatsappReady())) {
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message)); await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
} }
return 'sent'; return 'sent';
@@ -42,6 +42,7 @@ export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?:
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) { 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 (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD'); if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
if (method === 'whatsapp' && a.whatsappOptedOut) throw new TwoFactorError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page first.', 'BAD_METHOD');
if (method === 'totp') { if (method === 'totp') {
const secret = generateSecret(); const secret = generateSecret();
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {})); const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
@@ -0,0 +1,71 @@
/**
* The WhatsApp opt-out for every product (1.9.0, docs/APP-1.0-PLAN.md §8, decision 11). A STOP to
* the church's WhatsApp number reaches Accounts (a product's `whatsapp.optout`, or Accounts' own
* webhook for a church without Events). Accounts keeps it: the number in `WhatsAppOptOut`, and
* `whatsappOptedOut` on each account with it. Every linked product is told (`user.updated` carries
* `whatsapp_opted_out`) and sends that person no WhatsApp of any kind until they turn it back on
* on their account page here. Accounts itself sends them none either (codes go by email).
*/
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
import { audit, loginEvent } from '../lib/audit.js';
import { profileChanged, setNewsConsent } from './service.js';
/** What counts as STOP in a reply (English and Afrikaans), as Cross Events reads it. */
export function isStopKeyword(text: unknown): boolean {
return /^\s*(stop|stopp|unsubscribe|stop all|opt out|optout|uitteken)\s*[.!]?\s*$/i.test(String(text ?? ''));
}
/** A WAWP chat id (`27821234567@c.us`) → `+27821234567`; null for groups, channels and LIDs. */
export function phoneFromChatId(chatId: unknown): string | null {
const m = /^(\d{8,15})@c\.us$/.exec(String(chatId ?? ''));
return m ? `+${m[1]}` : null;
}
/**
* A STOP from `phone` (E.164): keeps the number, opts out every account with it (news on WhatsApp
* off too) and tells the products. Returns how many accounts have the number.
*/
export async function optOutNumber(ctx: Ctx, phone: string, opts: { keyword: string; source: string; receivedAt: Date }): Promise<number> {
await ctx.db.whatsAppOptOut.upsert({
where: { phone },
update: { keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt },
create: { phone, keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt, createdAt: ctx.now() },
});
const accounts = await ctx.db.account.findMany({ where: { phone, status: { not: 'deleted' } } });
for (const a of accounts) await optOut(ctx, a, opts.source);
await audit(ctx, { actorId: null, actorRole: 'system', action: 'whatsapp_opt_out', targetType: 'phone', targetId: null, metadata: { source: opts.source, keyword: opts.keyword, accounts: accounts.length } });
return accounts.length;
}
async function optOut(ctx: Ctx, a: Account, source: string) {
if (!a.whatsappOptedOut) {
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: true, whatsappOptedOutAt: ctx.now() } });
await loginEvent(ctx, a.id, 'whatsapp_opted_out', undefined, { detail: { source } });
}
await setNewsConsent(ctx, a, { whatsapp: false }, 'whatsapp_stop');
await profileChanged(ctx, a.id);
}
/** The person turns WhatsApp back on (their account page): the number's STOP is forgotten too. */
export async function optBackIn(ctx: Ctx, a: Account): Promise<boolean> {
if (!a.whatsappOptedOut) return false;
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: false, whatsappOptedOutAt: null } });
if (a.phone) await ctx.db.whatsAppOptOut.deleteMany({ where: { phone: a.phone } });
await loginEvent(ctx, a.id, 'whatsapp_opted_in');
await profileChanged(ctx, a.id);
return true;
}
/**
* After an account's phone number is set or changed: a number that replied STOP starts opted out.
* (A number without a STOP never turns an opt-out off: only the person does.) Returns whether it did.
*/
export async function applyKnownOptOut(ctx: Ctx, accountId: string): Promise<boolean> {
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
if (!a?.phone || a.whatsappOptedOut) return false;
const stop = await ctx.db.whatsAppOptOut.findUnique({ where: { phone: a.phone } });
if (!stop) return false;
await optOut(ctx, a, 'known_number');
return true;
}
+11
View File
@@ -11,6 +11,8 @@ import { ApiError, handle, limit, sendError } from '../http.js';
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js'; import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js'; import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js'; import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
import { messagingChanged, messagingParts } from '../links/messaging.js';
import { whatsappWebhookUrl } from '../links/whatsappWebhook.js';
import { currentSession } from '../oidc/sessions.js'; import { currentSession } from '../oidc/sessions.js';
import { signOutEverywhere } from '../oidc/sessions.js'; import { signOutEverywhere } from '../oidc/sessions.js';
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js'; import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
@@ -195,6 +197,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
changed.push(key); changed.push(key);
} }
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) }); await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
// 1.9.0: products sending with the church's settings (the App) fetch them again.
await messagingChanged(ctx, messagingParts(changed));
return { changed }; return { changed };
})); }));
@@ -209,6 +213,13 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
return { sent: true }; return { sent: true };
})); }));
// 1.9.0: WAWP's webhook address for STOP replies (a church without Cross Events points WAWP here).
r.get('/settings/whatsapp-webhook', handle(async (req, res) => {
await admin(req, res);
const linked = await ctx.db.productLink.findFirst({ where: { product: 'events' } });
return { ...(await whatsappWebhookUrl(ctx)), eventsLinked: !!linked };
}));
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone. // 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => { r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
const me = await admin(req, res); const me = await admin(req, res);
+4
View File
@@ -7,6 +7,7 @@
* /api/self/… the account page's own sign-in * /api/self/… the account page's own sign-in
* /api/church/v1, /api/links/v1/… for the church's other products * /api/church/v1, /api/links/v1/… for the church's other products
* /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0) * /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0)
* /api/v2/webhooks/whatsapp WAWP's webhook: STOP replies (1.9.0)
* /api/v2/… the pages' API (sign-in steps, account, admin, setup) * /api/v2/… the pages' API (sign-in steps, account, admin, setup)
*/ */
import express from 'express'; import express from 'express';
@@ -19,6 +20,7 @@ import { meRouter } from './me/routes.js';
import { LOGOUT_JS } from './oidc/pages.js'; import { LOGOUT_JS } from './oidc/pages.js';
import { publicRouter } from './public/routes.js'; import { publicRouter } from './public/routes.js';
import { requestsRouter } from './links/requests.js'; import { requestsRouter } from './links/requests.js';
import { whatsappWebhookRouter } from './links/whatsappWebhook.js';
import { setupRouter } from './setup/routes.js'; import { setupRouter } from './setup/routes.js';
import { health } from './hub/client.js'; import { health } from './hub/client.js';
import { appVersion } from './lib/version.js'; import { appVersion } from './lib/version.js';
@@ -50,6 +52,8 @@ export function createApp(ctx: Ctx, provider: Provider) {
app.use('/api/self', selfRouter(ctx)); app.use('/api/self', selfRouter(ctx));
app.use('/api', requestsRouter(ctx, provider)); app.use('/api', requestsRouter(ctx, provider));
app.use('/api', publicRouter(ctx)); app.use('/api', publicRouter(ctx));
// 1.9.0: WAWP's webhook (STOP replies), before the pages' API: no same-origin check, its own secret.
app.use(whatsappWebhookRouter(ctx));
const v2 = express.Router(); const v2 = express.Router();
v2.use(express.json({ limit: '64kb' })); v2.use(express.json({ limit: '64kb' }));
@@ -0,0 +1,94 @@
/**
* Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md §12, "Demo scenarios"): the
* scenario's church becomes the church profile (its own name, logo, icon, colours, campuses,
* service times and contact details), and its people get accounts. Loaded first, so Cross Events,
* the Website and the App then build their demo data around the same church and people.
*
* Only for demo sites (`crosscode demo <church> accounts --profile <scenario>`, which takes a backup
* first). People keep the same account id on every load (`demoId`), so products' copies still match.
* Demo people from before who aren't in this scenario are anonymised; real people (any address not at
* example.com) and Accounts admins are never touched.
*/
import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts';
import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo';
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import { hashPassword } from '../lib/passwords.js';
import { updateProfile } from '../church/profile.js';
import { currentNoticeVersion } from '../privacy/notice.js';
import { anonymise } from '../privacy/deletion.js';
/** Where Accounts serves the scenario's logo and icon (`/api/demo-assets/<scenario>/logo.svg`). */
export const DEMO_ASSETS_PATH = '/api/demo-assets';
const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const;
/** The SVG for a demo asset, or null for anything else. */
export function demoAsset(scenario: string, file: string): string | null {
const key = agent.demoScenarioSchema.safeParse(scenario);
const draw = (DEMO_ASSET_FILES as Record<string, (s: agent.DemoScenarioKey) => string>)[file];
return key.success && draw ? draw(key.data) : null;
}
export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number }
const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
const CHUNK = 500;
export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise<ScenarioResult> {
const { profile } = demoChurch(scenario);
const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`;
// The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed).
await updateProfile(ctx, {
name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale,
branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style },
campuses: profile.campuses, serviceTimes: profile.serviceTimes,
contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social,
});
// The people.
const people = demoPeople(scenario);
const wanted = new Set(people.map((p) => p.id));
const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a]));
let removed = 0;
for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) {
if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue;
await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } });
await anonymise(ctx, a.id);
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
removed++;
}
const passwordHash = await hashPassword(DEMO_PASSWORD);
const notice = await currentNoticeVersion(ctx);
const now = ctx.now();
const fields = (p: (typeof people)[number]) => ({
name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true,
phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const,
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now,
noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null,
whatsappOptedOut: false, whatsappOptedOutAt: null,
});
let updated = 0;
// Already here (this scenario loaded before, or anonymised when another was): brought back as they were.
for (const p of people) {
const a = existing.get(p.id);
if (!a) continue;
// Never take over a real person's account, nor an admin's.
if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue;
const other = await ctx.db.account.findUnique({ where: { email: p.email } });
if (other && other.id !== p.id) continue;
await ctx.db.account.update({ where: { id: p.id }, data: fields(p) });
updated++;
}
// New: in chunks, as the larger scenarios have a couple of thousand people.
const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email));
const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email));
for (let i = 0; i < fresh.length; i += CHUNK) {
await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) });
}
await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } });
await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() }));
return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed };
}
@@ -23,6 +23,7 @@ import { loginEvent } from '../lib/audit.js';
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js'; import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js'; import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
import { productName } from '../oidc/clients.js'; import { productName } from '../oidc/clients.js';
import { applyKnownOptOut } from '../accounts/whatsapp.js';
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done'; export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
@@ -115,7 +116,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
} }
if (stage === 'setup_two_factor') { if (stage === 'setup_two_factor') {
// Only the ways that can deliver a code now (1.2.0): an app always works. // Only the ways that can deliver a code now (1.2.0): an app always works.
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])]; extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone && !a.whatsappOptedOut ? ['whatsapp'] : [])];
extra.why = a.role === 'admin' ? 'admin' : 'product'; extra.why = a.role === 'admin' ? 'admin' : 'product';
} }
if (stage === 'notice') { if (stage === 'notice') {
@@ -177,6 +178,7 @@ export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<str
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } }); await 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 setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
await loginEvent(ctx, a.id, 'account_created'); await loginEvent(ctx, a.id, 'account_created');
await applyKnownOptOut(ctx, a.id);
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 }); return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
} }
+2 -1
View File
@@ -19,7 +19,8 @@ export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole
export type LoginEventType = export type LoginEventType =
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off' | 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created'; | 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created'
| 'whatsapp_opted_out' | 'whatsapp_opted_in';
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) { export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
try { try {
+1 -1
View File
@@ -5,7 +5,7 @@
import type { Ctx } from '../context.js'; import type { Ctx } from '../context.js';
/** Encrypted at rest; never sent to the browser. */ /** Encrypted at rest; never sent to the browser. */
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']); export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks', 'wawp_webhook_secret']);
/** The settings an admin may read and change through the generic settings API. */ /** The settings an admin may read and change through the generic settings API. */
export const ADMIN_SETTINGS = new Set([ export const ADMIN_SETTINGS = new Set([
@@ -1,12 +1,12 @@
/** /**
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1` * Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a * user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, `church.changed` and (1.9.0) `messaging.changed`. Each is a
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min, * `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, * 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
* export). * export).
*/ */
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts'; import { ACCOUNTS_CALL_PATH, CHURCH_PATHS, MESSAGING_CHANGED_PATH } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing'; import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js'; import type { Ctx } from '../context.js';
import { callSibling, siblingUrl } from './http.js'; import { callSibling, siblingUrl } from './http.js';
@@ -14,7 +14,10 @@ import { callSibling, siblingUrl } from './http.js';
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[]; 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 const MAX_ATTEMPTS = RETRY_MS.length + 1;
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed'; export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed' | 'messaging.changed';
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */ /** 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[] } = {}) { export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
@@ -23,7 +26,7 @@ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: str
for (const link of links) { for (const link of links) {
const callId = crypto.randomUUID(); const callId = crypto.randomUUID();
made.push(await ctx.db.delivery.create({ made.push(await ctx.db.delivery.create({
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() }, data: { linkId: link.installId, callId, type, path: PATHS[type] ?? ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
})); }));
} }
return made; return made;
@@ -0,0 +1,31 @@
/**
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 4): one set of email and WhatsApp settings per church,
* kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the
* Church App) are sent `messaging.changed` when they change, so they fetch them again.
*/
import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { queueCall } from './deliveries.js';
/** The settings that make up the church's email and WhatsApp. */
const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']);
const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']);
/** Which parts the changed setting keys touch. */
export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } {
return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) };
}
/**
* Records the change and tells every product that asked for the settings, except the one that
* made the change (`exceptLinkId`, e.g. Events saving its own into Accounts).
*/
export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) {
if (!parts.email && !parts.whatsapp) return;
const at = ctx.now().toISOString();
await ctx.settings.set('messaging_updated_at', at);
const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } });
const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId);
if (!linkIds.length) return;
await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds });
}
+46 -7
View File
@@ -18,7 +18,7 @@ import {
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema, ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult, type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
} from '@crosscode/contracts'; } from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing'; import { LINK_HEADERS, openLinkValue, sealLinkValue, verify } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js'; import type { Ctx } from '../context.js';
import type { ProductLink } from '../generated/prisma/client.js'; import type { ProductLink } from '../generated/prisma/client.js';
import { limit } from '../http.js'; import { limit } from '../http.js';
@@ -32,6 +32,8 @@ import { turnOff } from '../accounts/twoFactor.js';
import { signOutEverywhere } from '../oidc/sessions.js'; import { signOutEverywhere } from '../oidc/sessions.js';
import { anonymise } from '../privacy/deletion.js'; import { anonymise } from '../privacy/deletion.js';
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js'; import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js';
import { messagingChanged } from './messaging.js';
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */ /** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
const PROFILE_EDITORS = new Set(['website']); const PROFILE_EDITORS = new Set(['website']);
@@ -134,6 +136,7 @@ async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportP
for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } }); for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } });
await knows(ctx, link.installId, a.id, 'import', { upgrade: true }); await knows(ctx, link.installId, a.id, 'import', { upgrade: true });
await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } }); await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } });
await applyKnownOptOut(ctx, a.id);
} }
return { id: p.id, outcome: 'created', sub: p.id, reason: null }; return { id: p.id, outcome: 'created', sub: p.id, reason: null };
} }
@@ -225,6 +228,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
} }
const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } }); const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } });
await knows(ctx, link.installId, a.id, 'ensure'); await knows(ctx, link.installId, a.id, 'ensure');
await applyKnownOptOut(ctx, a.id);
const token = randomToken(); const token = randomToken();
// Only the product's own address: never somewhere else. // Only the product's own address: never somewhere else.
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url; const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
@@ -259,7 +263,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
if (Object.keys(data).length) { if (Object.keys(data).length) {
await ctx.db.account.update({ where: { id: a.id }, data }); await ctx.db.account.update({ where: { id: a.id }, data });
if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } }); if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } });
await profileChanged(ctx, a.id); if (!(data.phone && (await applyKnownOptOut(ctx, a.id)))) await profileChanged(ctx, a.id);
} }
await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) }); await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) });
return reply({ ok: true as const }); return reply({ ok: true as const });
@@ -323,10 +327,20 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') }); await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
return reply({ people }); return reply({ people });
} }
// contracts 1.20.0 (APP-1.0-PLAN §8): answered from Accounts 1.9.0. case 'messaging.get': {
case 'messaging.get': // 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings,
case 'whatsapp.optout': // secrets sealed with the link's secret. The product is sent messaging.changed from now on.
throw new RequestError(`This Accounts doesn't answer ${r.type} yet (Accounts 1.9.0 does).`, 'INVALID_REQUEST', 400); await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } });
const out = await messagingSettings(ctx, secret);
await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp });
return reply(out);
}
case 'whatsapp.optout': {
// 1.9.0 (decision 11): a STOP the product received. Kept here for every product.
const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) });
await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts });
return reply({ accounts });
}
case 'church.update': { case 'church.update': {
// The product checked the person's role (Accounts doesn't know the Website's); Accounts // The product checked the person's role (Accounts doesn't know the Website's); Accounts
// checks it's the Website, that the person signs in through it, and audits it as theirs. // checks it's the Website, that the person signs in through it, and audits it as theirs.
@@ -386,6 +400,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false }; whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
} }
} }
if (save && (email?.saved || whatsapp?.saved)) await messagingChanged(ctx, { email: !!email?.saved, whatsapp: !!whatsapp?.saved }, link.installId);
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } }); await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
const status = await messagingStatus(ctx); const status = await messagingStatus(ctx);
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } }); return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
@@ -423,7 +438,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
const out = await handle(ctx, provider, link, secret, request, req); const out = await handle(ctx, provider, link, secret, request, req);
// Checks write nothing, so they needn't be remembered. // Checks write nothing, so they needn't be remembered.
// people.check (1.5.0) only reads, and its reply holds profiles: never kept. // people.check (1.5.0) only reads, and its reply holds profiles: never kept.
const isCheck = ('check' in request && request.check) || request.type === 'people.check'; // messaging.get (1.9.0) carries sealed secrets: never kept either.
const isCheck = ('check' in request && request.check) || request.type === 'people.check' || request.type === 'messaging.get';
if (!isCheck) { if (!isCheck) {
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {}); await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
} }
@@ -469,6 +485,29 @@ async function messagingStatus(ctx: Ctx) {
}; };
} }
/**
* messaging.get (1.9.0): what Accounts sends with (its saved settings, else the server's .env),
* the password and token sealed with the link's secret. A part that isn't set up is null.
*/
async function messagingSettings(ctx: Ctx, secret: string) {
const s = ctx.settings;
const host = (await s.get('smtp_host')) || ctx.config.smtp?.host || null;
const port = Number((await s.get('smtp_port')) || ctx.config.smtp?.port || 587);
const pass = (await s.get('smtp_pass')) || ctx.config.smtp?.pass || '';
const from = (await s.get('smtp_from')) || ctx.config.smtp?.from || '';
const email = host && from ? {
host, port,
secure: (await s.get('smtp_secure')) === 'true' || (ctx.config.smtp?.secure ?? port === 465),
user: (await s.get('smtp_user')) || ctx.config.smtp?.user || '',
pass: pass ? sealLinkValue(secret, pass) : null,
from,
} : null;
const token = (await s.get('wawp_access_token')) || ctx.config.wawp?.accessToken || null;
const instanceId = (await s.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null;
const whatsapp = token && instanceId ? { accessToken: sealLinkValue(secret, token), instanceId } : null;
return { email, whatsapp, updatedAt: (await s.get('messaging_updated_at')) || null };
}
/** Old remembered requests (the `cleanup` job). */ /** Old remembered requests (the `cleanup` job). */
export async function forgetOldRequests(ctx: Ctx) { export async function forgetOldRequests(ctx: Ctx) {
return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } }); return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } });
@@ -0,0 +1,68 @@
/**
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 11): Accounts takes WAWP's webhook itself, for a church
* without Cross Events (a WAWP number sends replies to one address; with Events, Events receives
* them and passes a STOP on with `whatsapp.optout`).
*
* POST /api/v2/webhooks/whatsapp?secret=… (WAWP's `message` event)
*
* WAWP doesn't sign webhooks, so the address carries a secret only Accounts and WAWP know
* (Admin → Email and WhatsApp shows it to paste into WAWP). Always answers 200 quickly, so WAWP
* never retries; only a STOP from a phone number is acted on.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import type { Ctx } from '../context.js';
import { isStopKeyword, optOutNumber, phoneFromChatId } from '../accounts/whatsapp.js';
export const WHATSAPP_WEBHOOK_PATH = '/api/v2/webhooks/whatsapp';
/** The secret in the webhook's address, made on first use. */
async function webhookSecret(ctx: Ctx): Promise<string> {
const saved = await ctx.settings.get('wawp_webhook_secret');
if (saved) return saved;
const secret = crypto.randomBytes(24).toString('base64url');
await ctx.settings.set('wawp_webhook_secret', secret);
return secret;
}
/** The address to paste into WAWP's webhook settings (event: message), and when it last called. */
export async function whatsappWebhookUrl(ctx: Ctx) {
return {
url: `${ctx.config.publicUrl.replace(/\/$/, '')}${WHATSAPP_WEBHOOK_PATH}?secret=${encodeURIComponent(await webhookSecret(ctx))}`,
lastSeenAt: await ctx.settings.get('wawp_webhook_last_seen'),
};
}
function secretMatches(given: string, secret: string) {
return given.length === secret.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(secret));
}
export async function handleWhatsappWebhook(ctx: Ctx, query: { secret?: unknown }, body: unknown): Promise<'ignored' | 'seen' | 'stopped'> {
const secret = await ctx.settings.get('wawp_webhook_secret');
if (!secret || !secretMatches(String(query.secret ?? ''), secret)) return 'ignored';
await ctx.settings.set('wawp_webhook_last_seen', ctx.now().toISOString());
const payload = ((body as { payload?: Record<string, unknown> })?.payload ?? {}) as { fromMe?: boolean; body?: unknown; from?: unknown };
if (payload.fromMe || !isStopKeyword(payload.body)) return 'seen';
const phone = phoneFromChatId(payload.from);
// Groups, channels and senders WhatsApp only names by a "LID" have no number to opt out.
if (!phone) return 'seen';
await optOutNumber(ctx, phone, { keyword: String(payload.body).trim().toUpperCase().slice(0, 40), source: 'accounts', receivedAt: ctx.now() });
// The one message after a STOP: what it did and how to undo it.
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'the church';
await ctx.messenger.whatsapp({ to: phone, text: `You won't get WhatsApp messages from ${church} any more. To turn them back on, go to ${ctx.config.publicUrl.replace(/\/$/, '')}/account.` })
.catch((e: Error) => console.warn('[whatsapp webhook] confirmation not sent:', e.message));
return 'stopped';
}
export function whatsappWebhookRouter(ctx: Ctx) {
const r = express.Router();
r.post(WHATSAPP_WEBHOOK_PATH, express.json({ limit: '256kb' }), async (req: Request, res: Response) => {
try {
await handleWhatsappWebhook(ctx, req.query as { secret?: unknown }, req.body);
} catch (e) {
console.error('[whatsapp webhook]', (e as Error).message);
}
res.json({ ok: true });
});
return r;
}
+14 -3
View File
@@ -18,6 +18,7 @@ import { requestExport } from '../privacy/export.js';
import { requestDeletion } from '../privacy/deletion.js'; import { requestDeletion } from '../privacy/deletion.js';
import { hashToken, randomToken } from '../lib/crypto.js'; import { hashToken, randomToken } from '../lib/crypto.js';
import { linkedProducts } from '../links/store.js'; import { linkedProducts } from '../links/store.js';
import { applyKnownOptOut, optBackIn } from '../accounts/whatsapp.js';
/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */ /** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */
const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' }; const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' };
@@ -29,7 +30,9 @@ export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: numbe
return { return {
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, 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, phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion, news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
// 1.9.0: replied STOP to the church's WhatsApp number; turned back on here.
whatsappOptedOut: a.whatsappOptedOut, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
}; };
} }
@@ -80,7 +83,8 @@ export function meRouter(ctx: Ctx, provider: Provider) {
...(phone ? {} : { newsWhatsApp: false }), ...(phone ? {} : { newsWhatsApp: false }),
}, },
}); });
await profileChanged(ctx, s.account.id); // 1.9.0: a number that replied STOP starts opted out (which tells the products itself).
if (!(phone !== s.account.phone && (await applyKnownOptOut(ctx, s.account.id)))) await profileChanged(ctx, s.account.id);
return view(s); return view(s);
})); }));
@@ -175,11 +179,18 @@ export function meRouter(ctx: Ctx, provider: Provider) {
r.put('/me/news', handle(async (req, res) => { r.put('/me/news', handle(async (req, res) => {
const s = await signedIn(req, res); const s = await signedIn(req, res);
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page'); const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone && !s.account.whatsappOptedOut }, 'account_page');
if (changed) await profileChanged(ctx, s.account.id); if (changed) await profileChanged(ctx, s.account.id);
return view(s); return view(s);
})); }));
// 1.9.0: WhatsApp back on after a STOP (every product may send it again; news stays off until chosen).
r.post('/me/whatsapp-on', handle(async (req, res) => {
const s = await signedIn(req, res);
await optBackIn(ctx, s.account);
return view(s);
}));
r.get('/me/notice', handle(async (req, res) => { r.get('/me/notice', handle(async (req, res) => {
await signedIn(req, res); await signedIn(req, res);
const n = await currentNotice(ctx); const n = await currentNotice(ctx);
+1 -1
View File
@@ -27,7 +27,7 @@ async function ownPart(ctx: Ctx, accountId: string) {
return { return {
product: 'accounts', product: 'accounts',
sections: [ sections: [
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] }, { key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, whatsappOptedOut: a.whatsappOptedOut, whatsappOptedOutAt: a.whatsappOptedOutAt, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) }, { key: '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: '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 })) }, { key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
@@ -10,6 +10,7 @@ import { branding, church } from '../church/profile.js';
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js'; import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
import { setupNeeded } from '../setup/routes.js'; import { setupNeeded } from '../setup/routes.js';
import { currentNotice } from '../privacy/notice.js'; import { currentNotice } from '../privacy/notice.js';
import { DEMO_ASSETS_PATH, demoAsset } from '../demo/scenario.js';
const strip = (p: string) => p.replace(/^\/api/, ''); const strip = (p: string) => p.replace(/^\/api/, '');
@@ -31,6 +32,14 @@ export function publicRouter(ctx: Ctx) {
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt }; return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
})); }));
// 1.9.0: a demo scenario's logo and icon (drawn for the demo), which its church profile points at.
r.get(`${strip(DEMO_ASSETS_PATH)}/:scenario/:file`, limit(600), (req, res) => {
const svg = demoAsset(String(req.params.scenario), String(req.params.file));
if (!svg) return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such demo image.' } });
res.set({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'" });
return res.send(svg);
});
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => { r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
res.set('Cache-Control', 'public, max-age=60'); res.set('Cache-Control', 'public, max-age=60');
return church(ctx); return church(ctx);
@@ -0,0 +1,92 @@
// Accounts 1.9.0: a demo scenario's church and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { CHURCH_PATHS, churchSchema } from '@crosscode/contracts';
import { demoPeople } from '@crosscode/demo';
import { startHarness, type Harness } from './support/harness.js';
import { loadScenario } from '../src/demo/scenario.js';
import { church } from '../src/church/profile.js';
import { verifyPassword } from '../src/lib/passwords.js';
let h: Harness;
before(async () => { h = await startHarness(); });
after(async () => { await h.close(); });
const live = async () => h.db.account.findMany({ where: { status: { not: 'deleted' } } });
describe('loading a demo scenario', () => {
test('the church becomes the scenario\'s, with its own logo and icon, and the products are told', async () => {
const real = await h.makeAccount({ email: 'office@hope.test' });
const admin = await h.makeAccount({ email: 'admin.demo@example.com', role: 'admin' });
const r = await loadScenario(h.ctx, 'community-family');
assert.equal(r.church, 'Acacia Hill Church');
const c = await church(h.ctx);
assert.ok(churchSchema.safeParse(c).success);
assert.equal(c.name, 'Acacia Hill Church');
assert.equal(c.shortName, 'Acacia Hill');
assert.equal(c.branding.colours.primary, '#2f6f4f');
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'soft' });
assert.equal(c.branding.logoUrl, `${h.publicUrl}/api/demo-assets/community-family/logo.svg`);
assert.equal(c.contact.email, 'office.acaciahill@example.com');
assert.ok((await h.db.delivery.findMany({ where: { type: 'church.changed' } })).length >= 1);
// Real people and admins are never touched.
assert.equal((await h.db.account.findUnique({ where: { id: real.id } }))!.status, 'active');
assert.equal((await h.db.account.findUnique({ where: { id: admin.id } }))!.status, 'active');
});
test('every person has an account with the id the other products work out, and the demo password', async () => {
const people = demoPeople('community-family');
const ids = new Set((await live()).map((a) => a.id));
for (const p of people) assert.ok(ids.has(p.id), p.email);
const pastor = (await h.db.account.findUnique({ where: { id: people[0]!.id } }))!;
assert.equal(pastor.name, 'Thabo Nkosi');
assert.equal(pastor.emailVerified, true);
assert.ok(await verifyPassword('Demo@1234', pastor.passwordHash as string));
});
test('loading it again changes nobody\'s id', async () => {
const r = await loadScenario(h.ctx, 'community-family');
assert.equal(r.created, 0);
assert.equal(r.removed, 0);
assert.equal(r.updated, demoPeople('community-family').length);
});
test('another scenario replaces the demo people; switching back brings them back with the same ids', async () => {
const before = demoPeople('community-family');
const r = await loadScenario(h.ctx, 'bold-plant');
assert.equal(r.church, 'Harbour City Church');
assert.equal(r.removed, before.length);
assert.equal(r.created, demoPeople('bold-plant').length);
assert.equal((await h.db.account.findUnique({ where: { id: before[0]!.id } }))!.status, 'deleted');
assert.ok(await h.db.account.findUnique({ where: { email: 'office@hope.test' } }), 'a real person stays');
assert.equal((await h.db.account.findUnique({ where: { email: 'admin.demo@example.com' } }))!.status, 'active', 'an admin stays');
const back = await loadScenario(h.ctx, 'community-family');
assert.equal(back.updated, before.length);
const pastor = (await h.db.account.findUnique({ where: { id: before[0]!.id } }))!;
assert.equal(pastor.status, 'active');
assert.equal(pastor.email, before[0]!.email);
});
test('a scenario with campuses has them in the profile', async () => {
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church' }));
// Riverside has about 2 450 people; only its profile is checked here.
const c = await (async () => { await loadScenario(h.ctx, 'clean-campus'); return church(h.ctx); })();
assert.deepEqual(c.campuses.map((x) => x.slug), ['stellenbosch', 'paarl', 'somerset-west']);
assert.equal(c.serviceTimes.filter((s) => s.campus === 'stellenbosch').length, 2);
});
});
describe('demo logos', () => {
test('served as SVG for a scenario, 404 for anything else', async () => {
const res = await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/icon.svg`);
assert.equal(res.status, 200);
assert.equal(res.headers.get('content-type'), 'image/svg+xml; charset=utf-8');
assert.match(await res.text(), /^<svg[^>]*>.*#e4572e/);
const logo = await (await fetch(`${h.publicUrl}/api/demo-assets/heritage-parish/logo.svg`)).text();
assert.match(logo, /St Columba&apos;s Church/);
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/nowhere/icon.svg`)).status, 404);
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/secrets.txt`)).status, 404);
assert.equal((await fetch(`${h.publicUrl}${CHURCH_PATHS.profile}`)).status, 200);
});
});
@@ -12,7 +12,7 @@ const DEFAULTS: Record<string, () => Row> = {
account: () => ({ account: () => ({
givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active', 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, twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0,
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, whatsappOptedOut: false, whatsappOptedOutAt: null,
}), }),
recoveryCode: () => ({ usedAt: null }), recoveryCode: () => ({ usedAt: null }),
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }), pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
@@ -20,13 +20,13 @@ const DEFAULTS: Record<string, () => Row> = {
loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }), loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }),
privacyNotice: () => ({ publishedById: null }), privacyNotice: () => ({ publishedById: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }), auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
productLink: () => ({ connectedById: null, importStartedAt: null }), productLink: () => ({ connectedById: null, importStartedAt: null, messagingWantedAt: null }),
oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }), oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }),
delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }), delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }),
dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }), dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }),
deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }), deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }),
}; };
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' }; const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId', whatsAppOptOut: 'phone' };
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] }; const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']); const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
@@ -117,6 +117,10 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
table().set(row[key], row); table().set(row[key], row);
return clone(row); return clone(row);
}, },
createMany: async ({ data }: { data: Row[] }) => {
for (const d of data) await api.create({ data: d });
return { count: data.length };
},
update: async ({ where, data }: { where: Row; data: Row }) => { update: async ({ where, data }: { where: Row; data: Row }) => {
const r = findWhere(where); const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to update not found (${name})`); if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
@@ -0,0 +1,195 @@
// Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the church's email and WhatsApp settings for a product
// that sends with them (messaging.get, messaging.changed), and the WhatsApp opt-out for every
// product (whatsapp.optout, Accounts' own WAWP webhook, turning WhatsApp back on).
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { after, before, beforeEach, describe, test } from 'node:test';
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH, messagingChangedSchema, messagingGetReplySchema, userUpdatedSchema } from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, signedHeaders } from '@crosscode/contracts/signing';
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
import type { MemoryMessenger } from '../src/lib/messages.js';
import { runDue } from '../src/links/deliveries.js';
import { messagingChanged } from '../src/links/messaging.js';
import { handleWhatsappWebhook, whatsappWebhookUrl } from '../src/links/whatsappWebhook.js';
import { isStopKeyword, phoneFromChatId } from '../src/accounts/whatsapp.js';
let h: Harness;
let messenger: MemoryMessenger;
before(async () => { h = await startHarness(); messenger = h.messenger as MemoryMessenger; });
after(async () => { await h.close(); });
beforeEach(async () => {
h.received.length = 0;
messenger.whatsappOn = true;
messenger.whatsapps.length = 0;
await h.db.delivery.deleteMany({});
});
/** A request from the harness's linked product (signed with its link's secret). */
async function ask(body: Record<string, unknown>) {
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: PRODUCT_ID, secret: h.linkSecret, rawBody: raw }) } });
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
}
const sent = (path: string) => h.received.filter((r) => r.path === path).map((r) => JSON.parse(r.body) as Record<string, unknown>);
describe('messaging.get', () => {
test('nothing set up: both parts null', async () => {
const r = await ask({ type: 'messaging.get' });
assert.equal(r.status, 200, JSON.stringify(r.body));
assert.ok(messagingGetReplySchema.safeParse(r.body).success);
assert.equal(r.body.email, null);
assert.equal(r.body.whatsapp, null);
});
test('gives the settings with the password and token sealed for this link only, and never keeps the reply', async () => {
await h.ctx.settings.setMany({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_user: 'hello@hope.test', smtp_pass: 'mail-pass', smtp_from: 'hello@hope.test', wawp_access_token: 'wa-token', wawp_instance_id: 'HOPE01' });
const r = await ask({ type: 'messaging.get' });
assert.equal(r.status, 200, JSON.stringify(r.body));
const reply = messagingGetReplySchema.parse(r.body);
assert.equal(reply.email?.host, 'smtp.hope.test');
assert.equal(reply.email?.user, 'hello@hope.test');
assert.notEqual(reply.email?.pass, 'mail-pass');
assert.equal(openLinkValue(h.linkSecret, reply.email!.pass!), 'mail-pass');
assert.equal(openLinkValue(h.linkSecret, reply.whatsapp!.accessToken), 'wa-token');
assert.equal(reply.whatsapp?.instanceId, 'HOPE01');
assert.doesNotMatch(JSON.stringify(r.body), /mail-pass|wa-token/);
const link = await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } });
assert.ok(link?.messagingWantedAt, 'remembered as wanting messaging.changed');
assert.equal((await h.db.productRequest.findMany({ where: { type: 'messaging.get' } })).length, 0);
});
});
describe('messaging.changed', () => {
test('an admin changing WhatsApp tells the products that asked', async () => {
await ask({ type: 'messaging.get' });
await messagingChanged(h.ctx, { email: false, whatsapp: true });
await runDue(h.ctx);
const calls = sent(MESSAGING_CHANGED_PATH);
assert.equal(calls.length, 1);
assert.ok(messagingChangedSchema.safeParse(calls[0]).success);
assert.equal(calls[0]!.whatsapp, true);
assert.equal(calls[0]!.email, false);
assert.ok(h.received.find((x) => x.path === MESSAGING_CHANGED_PATH && h.signedByLink(x)), 'signed with the link');
assert.ok(await h.ctx.settings.get('messaging_updated_at'));
});
test('not to the product that made the change, nor for unrelated settings', async () => {
await ask({ type: 'messaging.get' });
await messagingChanged(h.ctx, { email: true, whatsapp: false }, PRODUCT_ID);
await messagingChanged(h.ctx, { email: false, whatsapp: false });
await runDue(h.ctx);
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
});
test('a product that never asked isn\'t told', async () => {
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { messagingWantedAt: null } });
await messagingChanged(h.ctx, { email: true, whatsapp: true });
await runDue(h.ctx);
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
});
});
describe('whatsapp.optout', () => {
test('opts out every account with the number, turns WhatsApp news off and tells the products', async () => {
const a = await h.makeAccount({ email: 'stop1@hope.test', phone: '+27825550001', phoneVerified: true, newsWhatsApp: true });
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550001', receivedAt: new Date().toISOString(), keyword: 'STOP' });
assert.equal(r.status, 200, JSON.stringify(r.body));
assert.equal(r.body.accounts, 1);
const after = (await h.db.account.findUnique({ where: { id: a.id } }))!;
assert.equal(after.whatsappOptedOut, true);
assert.equal(after.newsWhatsApp, false);
await runDue(h.ctx);
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).find((b) => b.type === 'user.updated' && b.sub === a.id);
assert.ok(updated, 'user.updated sent');
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, true);
});
test('keeps a number without an account: an account made with it later starts opted out', async () => {
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550002', receivedAt: new Date().toISOString(), keyword: 'STOP' });
assert.equal(r.body.accounts, 0);
const ensured = await ask({ type: 'people.ensure', name: 'Later Person', email: 'later@hope.test', phone: '+27825550002', returnUrl: `${h.productUrl}/` });
assert.equal(ensured.status, 200, JSON.stringify(ensured.body));
const a = (await h.db.account.findUnique({ where: { id: ensured.body.sub as string } }))!;
assert.equal(a.whatsappOptedOut, true);
});
test('a code for someone who replied STOP goes by email, never WhatsApp', async () => {
await h.makeAccount({ email: 'stop3@hope.test', password: 'Correct-horse-1', phone: '+27825550003', twoFactorMethod: 'whatsapp', whatsappOptedOut: true });
const r = await h.signIn(new Browser(), 'stop3@hope.test', 'Correct-horse-1');
assert.ok('pending' in r);
assert.equal(r.pending.stage, 'two_factor');
assert.match(String(r.pending.sentTo), /@hope\.test$/);
assert.equal(messenger.whatsapps.filter((w) => w.to === '+27825550003').length, 0);
});
});
describe('Accounts\' own WAWP webhook', () => {
const message = (from: string, body: string, fromMe = false) => ({ event: 'message', payload: { from, body, fromMe } });
test('reads STOP and phone numbers as Cross Events does', () => {
for (const s of ['STOP', ' stop ', 'Stop!', 'unsubscribe', 'STOPP', 'opt out']) assert.ok(isStopKeyword(s), s);
for (const s of ['stop the music', 'please stop', '', 'STOPPED']) assert.ok(!isStopKeyword(s), s);
assert.equal(phoneFromChatId('27825550004@c.us'), '+27825550004');
assert.equal(phoneFromChatId('1234567890-123@g.us'), null);
assert.equal(phoneFromChatId('12345@lid'), null);
});
test('ignores a call without the secret', async () => {
const { url } = await whatsappWebhookUrl(h.ctx);
assert.match(url, /\/api\/v2\/webhooks\/whatsapp\?secret=/);
await h.makeAccount({ email: 'stop4@hope.test', phone: '+27825550004' });
assert.equal(await handleWhatsappWebhook(h.ctx, { secret: 'wrong' }, message('27825550004@c.us', 'STOP')), 'ignored');
const res = await fetch(`${h.publicUrl}/api/v2/webhooks/whatsapp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550004@c.us', 'STOP')) });
assert.equal(res.status, 200);
assert.equal((await h.db.account.findUnique({ where: { email: 'stop4@hope.test' } }))!.whatsappOptedOut, false);
});
test('a STOP through the real address opts the number out and answers once', async () => {
const { url } = await whatsappWebhookUrl(h.ctx);
await h.makeAccount({ email: 'stop5@hope.test', phone: '+27825550005' });
const path = url.slice(url.indexOf('/api/'));
const res = await fetch(`${h.publicUrl}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550005@c.us', 'Stop')) });
assert.equal(res.status, 200);
assert.equal((await h.db.account.findUnique({ where: { email: 'stop5@hope.test' } }))!.whatsappOptedOut, true);
assert.ok(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550005' } }));
const replies = messenger.whatsapps.filter((w) => w.to === '+27825550005');
assert.equal(replies.length, 1);
assert.match(replies[0]!.text, /won't get WhatsApp messages from Hope Family Church/);
assert.ok((await whatsappWebhookUrl(h.ctx)).lastSeenAt);
});
test('other messages, and the church\'s own, change nothing', async () => {
const { url } = await whatsappWebhookUrl(h.ctx);
const secret = new URL(url).searchParams.get('secret');
await h.makeAccount({ email: 'stop6@hope.test', phone: '+27825550006' });
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'Thanks!')), 'seen');
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'STOP', true)), 'seen');
assert.equal((await h.db.account.findUnique({ where: { email: 'stop6@hope.test' } }))!.whatsappOptedOut, false);
});
});
describe('turning WhatsApp back on', () => {
test('on the account page: every product may send it again, and the number\'s STOP is forgotten', async () => {
await ask({ type: 'whatsapp.optout', phone: '+27825550007', receivedAt: new Date().toISOString(), keyword: 'STOP' });
const a = await h.makeAccount({ email: 'stop7@hope.test', password: 'Correct-horse-1', phone: '+27825550007', whatsappOptedOut: true, whatsappOptedOutAt: new Date() });
const browser = new Browser();
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'stop7@hope.test', password: 'Correct-horse-1' });
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
const me = await h.api(browser, 'GET', '/api/v2/me');
assert.equal(me.body.whatsappOptedOut, true);
// News on WhatsApp can't be ticked while it's off.
await h.api(browser, 'PUT', '/api/v2/me/news', { email: false, whatsapp: true });
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.newsWhatsApp, false);
const on = await h.api(browser, 'POST', '/api/v2/me/whatsapp-on');
assert.equal(on.status, 200, JSON.stringify(on.body));
assert.equal(on.body.whatsappOptedOut, false);
assert.equal(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550007' } }), null);
await runDue(h.ctx);
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).filter((b) => b.type === 'user.updated' && b.sub === a.id).at(-1);
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, false);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@crosscode/accounts-frontend", "name": "@crosscode/accounts-frontend",
"version": "1.8.0", "version": "1.9.0",
"private": true, "private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin", "description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": { "scripts": {
@@ -14,6 +14,7 @@ import { useExternalEffect } from "@/lib/hooks";
type Me = { type Me = {
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin"; 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 }; twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
whatsappOptedOut?: boolean;
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null; noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
}; };
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null }; type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
@@ -24,6 +25,7 @@ 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", 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", 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", signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
whatsapp_opted_out: "WhatsApp turned off (replied STOP)", whatsapp_opted_in: "WhatsApp turned back on",
}; };
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—"); const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
@@ -291,8 +293,17 @@ function Privacy({ me, onDone, onFail }: Props) {
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message); 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="email" label="Church news by email" defaultChecked={me.news.email} />
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} /> <Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone || me.whatsappOptedOut} hint={!me.phone ? "Add your mobile number first." : me.whatsappOptedOut ? "WhatsApp is off: see below." : undefined} />
</form> </form>
{me.whatsappOptedOut && (
<div className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm">
<p className="mb-2">You replied STOP to the church&apos;s WhatsApp number, so none of the church&apos;s sites send you WhatsApp messages (reminders and codes come by email instead).</p>
<Button variant="secondary" onClick={async () => {
const r = await call("POST", "/me/whatsapp-on");
if (r.ok) onDone("WhatsApp is back on. Church news on WhatsApp stays off until you tick it."); else onFail(r.error.message);
}}>Turn WhatsApp back on</Button>
</div>
)}
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p> <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"> <div className="border-t pt-4">
@@ -71,6 +71,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
{section === "messages" && <> {section === "messages" && <>
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} /> <Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} /> <Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
<WhatsAppReplies />
</>} </>}
{section === "notice" && <NoticeTab flash={flash} />} {section === "notice" && <NoticeTab flash={flash} />}
{section === "backups" && <Backups flash={flash} />} {section === "backups" && <Backups flash={flash} />}
@@ -446,6 +447,29 @@ function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: strin
); );
} }
/** 1.9.0: where WAWP sends replies, so a STOP reaches Accounts (only needed without Cross Events). */
function WhatsAppReplies() {
const [data, setData] = useState<{ url: string; lastSeenAt: string | null; eventsLinked: boolean } | null>(null);
useExternalEffect(() => {
let alive = true;
call<{ url: string; lastSeenAt: string | null; eventsLinked: boolean }>("GET", "/admin/settings/whatsapp-webhook").then((r) => { if (alive && r.ok) setData(r.data); });
return () => { alive = false; };
}, []);
if (!data) return null;
return (
<Card>
<Heading icon={<MessageCircle className="h-4 w-4" />} sub="Someone who replies STOP to the church's WhatsApp number gets no WhatsApp from any of the church's sites until they turn it back on on their account page.">WhatsApp replies (STOP)</Heading>
{data.eventsLinked
? <p className="text-sm text-gray-600">Cross Events receives the replies and passes a STOP on to Accounts. Keep WAWP&apos;s webhook pointing at Cross Events.</p>
: <>
<p className="mb-2 text-sm text-gray-600">In WAWP, set the webhook (event: message) to this address:</p>
<input readOnly className="mb-2 w-full rounded border bg-gray-50 px-2 py-1 font-mono text-xs" value={data.url} onFocus={(e) => e.currentTarget.select()} aria-label="Webhook address" />
<p className="text-sm text-gray-600">{data.lastSeenAt ? `Last message received: ${new Date(data.lastSeenAt).toLocaleString("en-ZA")}.` : "No message received through it yet."}</p>
</>}
</Card>
);
}
// ─── Privacy notice, licence, audit ─────────────────────────────────────────── // ─── Privacy notice, licence, audit ───────────────────────────────────────────
type NoticeVersion = { version: number; title: string; body: string }; type NoticeVersion = { version: number; title: string; body: string };
+5 -3
View File
@@ -454,9 +454,11 @@ data that describes **the same church**, so a demo shows the three products work
Website's demo keeps the profile and only uses the church's name). It's a demo client, so nothing Website's demo keeps the profile and only uses the church's name). It's a demo client, so nothing
real is lost; the profile before the load goes in the backup taken first. Each scenario has: real is lost; the profile before the load goes in the backup taken first. Each scenario has:
- a name, short name and a **logo and icon** of its own (made for the demo, a simple mark and - a name, short name and a **logo and icon** of its own (made for the demo, a simple mark and
wordmark per church, never a real church's), in `apps/accounts/backend/demo-assets/<scenario>/` wordmark per church, never a real church's), drawn as SVG by `@crosscode/demo` (Accounts
with a credits file. Accounts serves them itself (`/demo-assets/…`), since its profile holds 1.9.0). Accounts serves them itself (`/api/demo-assets/<scenario>/logo.svg`, `icon.svg`), since
addresses, not uploads; its profile holds addresses, not uploads;
- its people, also in `@crosscode/demo` (`demoPeople`), with the same account id in every
product (`demoId`), so each product's loader builds around the same people;
- colours, font pairing, corners and the Website template's style that suit it; - colours, font pairing, corners and the Website template's style that suit it;
- a street address, campuses, service times, phone, email (`@example.com`) and social links - a street address, campuses, service times, phone, email (`@example.com`) and social links
(to `example.com` addresses), a timezone, and the product links to the client's installs; (to `example.com` addresses), a timezone, and the product links to the client's installs;
+12 -2
View File
@@ -12,12 +12,12 @@ separately below; the two often differ.
|------|------|--------|-----|----------| |------|------|--------|-----|----------|
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.2** | `events@3.7.2` | 2026-11-27 | | Cross Events | `crosscode-platform` (`apps/events`) | **3.7.2** | `events@3.7.2` | 2026-11-27 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 | | Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 | | Accounts | `crosscode-platform` (`apps/accounts`) | **1.9.0** | `accounts@1.9.0` | 2026-11-30 |
| Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 | | Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.21.0** | `contracts@1.21.0` | 2026-11-30 | | Contracts | `crosscode-platform` (`packages/contracts`) | **1.21.0** | `contracts@1.21.0` | 2026-11-30 |
| Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 | | Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 |
| crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 | | crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: an uninstall keeps the Website's backup snapshots shared, `rsync -aH`) | | `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-30 (last change: `crosscode demo <church> accounts --profile <scenario>`, `--scenario` on every demo, Accounts builds `packages/demo`) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main` The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
on each run, so merging to `main` and pushing releases it. Its changes are listed in on each run, so merging to `main` and pushing releases it. Its changes are listed in
@@ -28,6 +28,7 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
| What | Where | Version in package.json | | What | Where | Version in package.json |
|------|-------|-------------------------| |------|-------|-------------------------|
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) | | `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
| `@crosscode/demo` | `packages/demo` | 1.0.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0) |
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) | | `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) | | `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
| Website | `apps/website` | 1.7.1 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28; installed for the demo church cross-demo2 (1.7.1) only, Hope Family Church next) | | Website | `apps/website` | 1.7.1 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28; installed for the demo church cross-demo2 (1.7.1) only, Hope Family Church next) |
@@ -38,6 +39,15 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for ## What each latest release was for
- **Accounts 1.9.0 + `@crosscode/demo` 1.0.0 + crosscode script (2026-11-30):** Church App
groundwork (APP-1.0-PLAN §8, §12): `messaging.get` and `messaging.changed`; the WhatsApp opt-out
for every product (`whatsapp.optout`, Accounts' own WAWP webhook, `whatsapp_opted_out`, "Turn
WhatsApp back on"); a demo scenario's church profile, SVG logo and icon, and people
(`crosscode demo <church> accounts --profile <scenario>`). **One migration.** Needs contracts
1.21.0 and `packages/demo` (the `crosscode` script on `main` installs and builds it). Checked:
Accounts' tests (99), `@crosscode/demo`'s (8), the script's bats (111), the workspace typecheck
and lint, and on PostgreSQL 18 the migrations, scenario loads (2 457 people in 3.4 s), the
opt-out and `npm run demo`. Not deployed yet.
- **Contracts 1.21.0 (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): `agent.DEMO_SCENARIOS`, - **Contracts 1.21.0 (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): `agent.DEMO_SCENARIOS`,
eight fictional churches, one per Website demo profile, that load Accounts, Events, the Website eight fictional churches, one per Website demo profile, that load Accounts, Events, the Website
and the App alike; `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS`, a profile per and the App alike; `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS`, a profile per
+15 -2
View File
@@ -51,10 +51,11 @@
}, },
"apps/accounts/backend": { "apps/accounts/backend": {
"name": "@crosscode/accounts-backend", "name": "@crosscode/accounts-backend",
"version": "1.8.0", "version": "1.9.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/demo": "*",
"@node-rs/argon2": "^2.2.2", "@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1", "@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1", "@prisma/client": "^7.10.1",
@@ -88,7 +89,7 @@
}, },
"apps/accounts/frontend": { "apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend", "name": "@crosscode/accounts-frontend",
"version": "1.8.0", "version": "1.9.0",
"dependencies": { "dependencies": {
"@crosscode/contracts": "*", "@crosscode/contracts": "*",
"@crosscode/ui": "*", "@crosscode/ui": "*",
@@ -1066,6 +1067,10 @@
"resolved": "packages/contracts", "resolved": "packages/contracts",
"link": true "link": true
}, },
"node_modules/@crosscode/demo": {
"resolved": "packages/demo",
"link": true
},
"node_modules/@crosscode/events-backend": { "node_modules/@crosscode/events-backend": {
"resolved": "apps/events/backend", "resolved": "apps/events/backend",
"link": true "link": true
@@ -23219,6 +23224,14 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"packages/demo": {
"name": "@crosscode/demo",
"version": "1.0.0",
"license": "UNLICENSED",
"dependencies": {
"@crosscode/contracts": "*"
}
},
"packages/seo": { "packages/seo": {
"name": "@crosscode/seo", "name": "@crosscode/seo",
"version": "1.0.0", "version": "1.0.0",
+15
View File
@@ -0,0 +1,15 @@
# @crosscode/demo
The demo scenarios' churches and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios"). Loading a
scenario on a demo client puts the same church into every product: Accounts takes the church
profile, logo, icon and people from here, and Cross Events, the Church Website and the App build
their demo data around the same people (same `sub` in every product: `demoId`).
- `DEMO_CHURCHES`, `demoChurch(scenario)`: each church's profile (name, colours, font pairing,
corners, campuses, service times, contact, social links) and the mark its logo is drawn with.
- `demoPeople(scenario)`: the leads (pastor, office, prayer coordinator…) and members, enough for
the scenario's App active-member band. `demoParts(scenario)`: what each lead does.
- `demoIconSvg`, `demoLogoSvg`: the logo and icon, drawn for the demo.
Everything is fictional: people and church addresses are at `example.com`, there are no phone
numbers, and the password is `Demo@1234`. Ships inside the apps that use it (not tagged).
+7
View File
@@ -0,0 +1,7 @@
module.exports = {
testEnvironment: "node",
testMatch: ["<rootDir>/tests/**/*.test.ts"],
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
moduleFileExtensions: ["ts", "js", "json"],
modulePathIgnorePatterns: ["<rootDir>/dist/"],
};
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@crosscode/demo",
"version": "1.0.0",
"private": true,
"description": "The demo scenarios' churches and people (APP-1.0-PLAN §12): the same church in Accounts, Cross Events, the Church Website and the App. Fictional only.",
"license": "UNLICENSED",
"type": "commonjs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"./package.json": "./package.json"
},
"files": [
"dist",
"README.md"
],
"sideEffects": false,
"scripts": {
"build": "tsup",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "jest"
},
"dependencies": {
"@crosscode/contracts": "*"
}
}
+166
View File
@@ -0,0 +1,166 @@
import type { BrandStyle, Church, agent } from "@crosscode/contracts";
/**
* Each demo scenario's church (APP-1.0-PLAN §12, "Demo scenarios"; the list is
* `agent.DEMO_SCENARIOS` in the contracts). Loading a scenario puts this profile into Accounts, so
* Cross Events, the Website and the App all show the same church. Every name, address and number is
* made up: contact addresses are at example.com, social links at example.com, and there are no
* phone numbers (nothing a demo sends can reach a real person).
*/
/** The simple mark each church's logo and icon are drawn with (`./logo`). */
export type DemoMark = "arch" | "cross" | "flame" | "wave" | "tree" | "sun" | "north" | "river";
/** The profile fields Accounts takes from a scenario (it fills in the rest: ids, links, logo addresses). */
export type DemoChurchProfile = Pick<Church, "name" | "shortName" | "timezone" | "locale" | "campuses" | "serviceTimes" | "social"> & {
colours: { primary: string; accent: string };
style: { fontPairing: NonNullable<BrandStyle["fontPairing"]>; corners: NonNullable<BrandStyle["corners"]> };
contact: Omit<Church["contact"], "phone" | "whatsapp">;
};
export interface DemoChurch {
scenario: agent.DemoScenarioKey;
/** Used in demo addresses: `office.<slug>@example.com`. */
slug: string;
mark: DemoMark;
profile: DemoChurchProfile;
}
const ZA = "Africa/Johannesburg";
const address = (line1: string, suburb: string | null, city: string, province: string, postalCode: string) =>
({ line1, line2: null, suburb, city, province, postalCode, country: "ZA", geo: null });
const social = (slug: string, networks: ("facebook" | "instagram" | "youtube" | "spotify")[]) =>
networks.map((network) => ({ network, url: `https://example.com/${network}/${slug}` }));
const contact = (slug: string, addr: ReturnType<typeof address>) => ({ email: `office.${slug}@example.com`, address: addr });
export const DEMO_CHURCHES: readonly DemoChurch[] = [
{
scenario: "heritage-parish", slug: "stcolumbas", mark: "arch",
profile: {
name: "St Columba's Church", shortName: "St Columba's", timezone: ZA, locale: "en-ZA",
colours: { primary: "#5b2333", accent: "#c9a227" }, style: { fontPairing: "classic", corners: "sharp" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "09:00", label: "Sung Eucharist", campus: null, note: "Sunday school in the hall during the service" },
{ day: "wednesday", time: "10:00", label: "Midweek communion", campus: null, note: null },
],
contact: contact("stcolumbas", address("3 Glebe Lane", "Old Town", "Grahamstown", "Eastern Cape", "6139")),
social: social("stcolumbas", ["facebook"]),
},
},
{
scenario: "heritage-city", slug: "gracecathedral", mark: "cross",
profile: {
name: "Grace Cathedral", shortName: "Grace", timezone: ZA, locale: "en-ZA",
colours: { primary: "#1d3557", accent: "#e09f3e" }, style: { fontPairing: "editorial", corners: "sharp" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "07:30", label: "Early communion", campus: null, note: null },
{ day: "sunday", time: "09:30", label: "Cathedral Eucharist", campus: null, note: "Choir and children's church" },
{ day: "sunday", time: "18:00", label: "Choral evensong", campus: null, note: null },
{ day: "wednesday", time: "12:30", label: "Lunchtime prayer", campus: null, note: "Thirty minutes, then soup in the crypt" },
],
contact: contact("gracecathedral", address("1 Cathedral Square", "City Centre", "Cape Town", "Western Cape", "8001")),
social: social("gracecathedral", ["facebook", "youtube", "spotify"]),
},
},
{
scenario: "bold-youth", slug: "ignite", mark: "flame",
profile: {
name: "Ignite Church", shortName: "Ignite", timezone: ZA, locale: "en-ZA",
colours: { primary: "#e4572e", accent: "#17bebb" }, style: { fontPairing: "impact", corners: "round" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "10:00", label: "Sunday gathering", campus: null, note: "Kids zone for ages 3 to 11" },
{ day: "sunday", time: "17:30", label: "Ignite Night", campus: null, note: "Worship night for students and young adults" },
{ day: "friday", time: "19:00", label: "Youth", campus: null, note: "Grades 8 to 12" },
],
contact: contact("ignite", address("48 Factory Road", "Maboneng", "Johannesburg", "Gauteng", "2094")),
social: social("ignite", ["instagram", "youtube", "spotify"]),
},
},
{
scenario: "bold-plant", slug: "harbourcity", mark: "wave",
profile: {
name: "Harbour City Church", shortName: "Harbour City", timezone: ZA, locale: "en-ZA",
colours: { primary: "#0b6e99", accent: "#f4b942" }, style: { fontPairing: "contemporary", corners: "round" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "09:30", label: "Sunday service", campus: null, note: "In the hall of Seaview Primary School" },
],
contact: contact("harbourcity", address("Seaview Primary School, 12 Marine Drive", "Humewood", "Gqeberha", "Eastern Cape", "6001")),
social: social("harbourcity", ["instagram", "facebook"]),
},
},
{
scenario: "community-family", slug: "acaciahill", mark: "tree",
profile: {
name: "Acacia Hill Church", shortName: "Acacia Hill", timezone: ZA, locale: "en-ZA",
colours: { primary: "#2f6f4f", accent: "#e9a23b" }, style: { fontPairing: "warm", corners: "soft" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "08:30", label: "Early service", campus: null, note: null },
{ day: "sunday", time: "10:30", label: "Family service", campus: null, note: "Kids' church for ages 2 to 12" },
{ day: "wednesday", time: "18:30", label: "Prayer evening", campus: null, note: null },
],
contact: contact("acaciahill", address("27 Acacia Avenue", "Lynnwood", "Pretoria", "Gauteng", "0081")),
social: social("acaciahill", ["facebook", "instagram", "youtube"]),
},
},
{
scenario: "community-town", slug: "karoo", mark: "sun",
profile: {
name: "Karoo Gemeenskapskerk", shortName: "Karoo Kerk", timezone: ZA, locale: "af-ZA",
colours: { primary: "#9c4a1a", accent: "#d9b44a" }, style: { fontPairing: "friendly", corners: "soft" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "09:00", label: "Erediens", campus: null, note: "Kinderkerk tydens die diens" },
{ day: "sunday", time: "18:00", label: "Aanddiens (English)", campus: null, note: null },
{ day: "wednesday", time: "19:00", label: "Bidstond", campus: null, note: null },
],
contact: contact("karoo", address("14 Kerkstraat", null, "Graaff-Reinet", "Eastern Cape", "6280")),
social: social("karoo", ["facebook"]),
},
},
{
scenario: "clean-modern", slug: "northpoint", mark: "north",
profile: {
name: "Northpoint Church", shortName: "Northpoint", timezone: ZA, locale: "en-ZA",
colours: { primary: "#22313f", accent: "#3fb68b" }, style: { fontPairing: "modern", corners: "soft" },
campuses: [],
serviceTimes: [
{ day: "sunday", time: "08:30", label: "First service", campus: null, note: null },
{ day: "sunday", time: "10:30", label: "Second service", campus: null, note: "Kids and youth during the service" },
{ day: "sunday", time: "18:00", label: "Evening service", campus: null, note: null },
],
contact: contact("northpoint", address("200 Northpoint Boulevard", "Umhlanga Ridge", "Durban", "KwaZulu-Natal", "4319")),
social: social("northpoint", ["facebook", "instagram", "youtube", "spotify"]),
},
},
{
scenario: "clean-campus", slug: "riverside", mark: "river",
profile: {
name: "Riverside Church", shortName: "Riverside", timezone: ZA, locale: "en-ZA",
colours: { primary: "#264653", accent: "#2a9d8f" }, style: { fontPairing: "modern", corners: "sharp" },
campuses: [
{ slug: "stellenbosch", name: "Stellenbosch", address: address("5 Riverbank Road", "Die Boord", "Stellenbosch", "Western Cape", "7600") },
{ slug: "paarl", name: "Paarl", address: address("88 Main Road", "Paarl Central", "Paarl", "Western Cape", "7646") },
{ slug: "somerset-west", name: "Somerset West", address: address("12 Lourens Street", null, "Somerset West", "Western Cape", "7130") },
],
serviceTimes: [
{ day: "sunday", time: "09:00", label: "Morning service", campus: "stellenbosch", note: null },
{ day: "sunday", time: "18:30", label: "Students' service", campus: "stellenbosch", note: "Supper afterwards in the courtyard" },
{ day: "sunday", time: "09:30", label: "Morning service", campus: "paarl", note: "Kids' church during the service" },
{ day: "sunday", time: "10:00", label: "Morning service", campus: "somerset-west", note: null },
],
contact: contact("riverside", address("5 Riverbank Road", "Die Boord", "Stellenbosch", "Western Cape", "7600")),
social: social("riverside", ["instagram", "youtube"]),
},
},
];
export function demoChurch(scenario: agent.DemoScenarioKey): DemoChurch {
const c = DEMO_CHURCHES.find((x) => x.scenario === scenario);
if (!c) throw new Error(`No demo church for ${scenario}`);
return c;
}
+8
View File
@@ -0,0 +1,8 @@
/**
* @crosscode/demo: the demo scenarios' churches and people (docs/APP-1.0-PLAN.md §12, "Demo
* scenarios"), so Accounts, Cross Events, the Church Website and the App load the same church.
* The scenario list itself is `agent.DEMO_SCENARIOS` in @crosscode/contracts. Fictional only.
*/
export * from "./churches";
export * from "./people";
export * from "./logo";
+47
View File
@@ -0,0 +1,47 @@
import { FONT_PAIRINGS, type agent } from "@crosscode/contracts";
import { demoChurch, type DemoMark } from "./churches";
/**
* Each demo church's logo and icon, drawn for the demo (never a real church's): a simple mark in
* white on the church's colour, and the mark beside the church's name. SVG, so they're crisp at
* any size; Accounts serves them (`/api/demo-assets/<scenario>/icon.svg`, `logo.svg`).
*/
/** The marks, drawn in white on a 512 × 512 square. */
const MARKS: Record<DemoMark, string> = {
// A church window: a pointed arch with a sill.
arch: '<path d="M176 400V236c0-56 36-100 80-124 44 24 80 68 80 124v164z" fill="none" stroke="#fff" stroke-width="28" stroke-linejoin="round"/><path d="M256 168v232M176 272h160" stroke="#fff" stroke-width="20"/>',
cross: '<rect x="232" y="96" width="48" height="320" rx="6" fill="#fff"/><rect x="152" y="176" width="208" height="48" rx="6" fill="#fff"/>',
flame: '<path d="M256 88c24 72 104 112 104 200a104 104 0 0 1-208 0c0-48 24-80 48-104 0 40 16 64 40 72-8-64 0-112 16-168z" fill="#fff"/>',
wave: '<path d="M96 300c40-40 80-40 120 0s80 40 120 0 80-40 80 0M96 372c40-40 80-40 120 0s80 40 120 0 80-40 80 0" fill="none" stroke="#fff" stroke-width="28" stroke-linecap="round"/><path d="M256 108v120M216 148h80" stroke="#fff" stroke-width="24" stroke-linecap="round"/>',
// An acacia: a flat crown on a thin trunk.
tree: '<path d="M112 220c0-36 64-64 144-64s144 28 144 64-64 44-144 44-144-8-144-44z" fill="#fff"/><path d="M256 260v156M256 316l-56-52M256 300l52-40" stroke="#fff" stroke-width="22" stroke-linecap="round"/>',
sun: '<circle cx="256" cy="300" r="72" fill="#fff"/><path d="M256 156v-48M156 204l-34-34M356 204l34-34M120 300H72M392 300h48" stroke="#fff" stroke-width="24" stroke-linecap="round"/><path d="M96 404h320" stroke="#fff" stroke-width="24" stroke-linecap="round"/>',
// A compass point.
north: '<path d="M256 88l88 296-88-56-88 56z" fill="#fff"/><circle cx="256" cy="420" r="16" fill="#fff"/>',
// A river through three points (three campuses).
river: '<path d="M120 120c120 40 40 140 136 168s48 112 136 104" fill="none" stroke="#fff" stroke-width="32" stroke-linecap="round"/><circle cx="148" cy="360" r="28" fill="#fff"/><circle cx="380" cy="160" r="28" fill="#fff"/><circle cx="256" cy="200" r="20" fill="#fff"/>',
};
const escapeXml = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
/** The square icon (app icon, favicon): the mark on the church's primary colour. */
export function demoIconSvg(scenario: agent.DemoScenarioKey): string {
const c = demoChurch(scenario);
const radius = c.profile.style.corners === "sharp" ? 48 : c.profile.style.corners === "round" ? 160 : 96;
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" role="img" aria-label="${escapeXml(c.profile.name)}"><rect width="512" height="512" rx="${radius}" fill="${c.profile.colours.primary}"/>${MARKS[c.mark]}</svg>`;
}
/** The logo: the icon and the church's name in its heading font (a font stack, with a fallback). */
export function demoLogoSvg(scenario: agent.DemoScenarioKey): string {
const c = demoChurch(scenario);
const pairing = FONT_PAIRINGS[c.profile.style.fontPairing];
const font = `${pairing.heading.family}, ${pairing.heading.category === "serif" ? "Georgia, serif" : "Helvetica, Arial, sans-serif"}`;
const name = c.profile.name;
const size = name.length > 20 ? 64 : 76;
const width = Math.round(240 + name.length * size * 0.56);
const icon = demoIconSvg(scenario).replace(/^<svg[^>]*>/, "").replace(/<\/svg>$/, "");
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} 200" width="${width}" height="200" role="img" aria-label="${escapeXml(name)}">`
+ `<svg x="16" y="16" width="168" height="168" viewBox="0 0 512 512">${icon}</svg>`
+ `<text x="208" y="${100 + size * 0.35}" font-family="${escapeXml(font)}" font-size="${size}" font-weight="700" fill="${c.profile.colours.primary}">${escapeXml(name)}</text></svg>`;
}
+116
View File
@@ -0,0 +1,116 @@
import { agent, DEMO_EMAIL_DOMAIN } from "@crosscode/contracts";
import { demoChurch } from "./churches";
/**
* Each scenario's people (APP-1.0-PLAN §12): a handful with parts to play in every product (the
* pastor, the office, the prayer coordinator…) and members enough to put the App in the scenario's
* active-member band. All at example.com (`DEMO_EMAIL_DOMAIN`, reserved: no real person has one), no
* phone numbers, password `Demo@1234`. Ids are worked out from the email, so a person keeps the
* same account (`sub`) every time a scenario is loaded, in every product.
*/
export const DEMO_PASSWORD = "Demo@1234";
/** What someone does at the church; each product turns it into its own roles. */
export const DEMO_PARTS = ["pastor", "office", "prayer-coordinator", "devotional-writer", "worship", "kids", "youth", "member"] as const;
export type DemoPart = (typeof DEMO_PARTS)[number];
export interface DemoPerson {
/** The account id (`sub`): the same on every load. */
id: string;
name: string;
givenName: string;
familyName: string;
email: string;
part: DemoPart;
/** The campus they belong to (multi-campus scenarios), or null. */
campus: string | null;
}
type Lead = [part: DemoPart, given: string, family: string];
/** The people with parts, per scenario. */
const LEADS: Record<agent.DemoScenarioKey, Lead[]> = {
"heritage-parish": [["pastor", "Margaret", "Ashworth"], ["office", "Gillian", "Fortuin"], ["prayer-coordinator", "Desmond", "Botha"], ["devotional-writer", "Rosemary", "Kleinhans"], ["worship", "Edward", "Mbeki"], ["kids", "Joyce", "Petersen"]],
"heritage-city": [["pastor", "Jonathan", "Hartley"], ["office", "Nomvula", "Dube"], ["prayer-coordinator", "Abigail", "Jacobs"], ["devotional-writer", "Samuel", "Okafor"], ["worship", "Clara", "Van Wyk"], ["kids", "Thembeka", "Mthembu"], ["youth", "Daniel", "Pillay"]],
"bold-youth": [["pastor", "Kagiso", "Molefe"], ["office", "Zinhle", "Khumalo"], ["prayer-coordinator", "Liam", "Fourie"], ["devotional-writer", "Ayanda", "Ngcobo"], ["worship", "Jade", "Adams"], ["kids", "Precious", "Mokoena"], ["youth", "Tumi", "Sithole"]],
"bold-plant": [["pastor", "Sipho", "Mahlangu"], ["office", "Megan", "Coetzee"], ["prayer-coordinator", "Lerato", "Mashaba"], ["devotional-writer", "Sipho", "Mahlangu"], ["worship", "Ruan", "Steyn"], ["kids", "Amahle", "Zulu"]],
"community-family": [["pastor", "Thabo", "Nkosi"], ["office", "Linda", "Venter"], ["prayer-coordinator", "Lindiwe", "Mabaso"], ["devotional-writer", "Grace", "Naidoo"], ["worship", "Pieter", "Du Toit"], ["kids", "Naledi", "Radebe"], ["youth", "Johan", "Botes"]],
"community-town": [["pastor", "Hendrik", "Lombard"], ["office", "Annatjie", "Smit"], ["prayer-coordinator", "Magda", "Vermeulen"], ["devotional-writer", "Hendrik", "Lombard"], ["worship", "Wilhelm", "Kruger"], ["kids", "Elize", "Nel"], ["youth", "Dewald", "Jansen"]],
"clean-modern": [["pastor", "Michael", "Reddy"], ["office", "Sarah", "Govender"], ["prayer-coordinator", "Nandi", "Cele"], ["devotional-writer", "Chris", "Marais"], ["worship", "Kayla", "Moodley"], ["kids", "Bongani", "Shabalala"], ["youth", "Ethan", "Brink"]],
"clean-campus": [["pastor", "David", "Le Roux"], ["office", "Palesa", "Mofokeng"], ["prayer-coordinator", "Hannah", "Swart"], ["devotional-writer", "Lwazi", "Mkhize"], ["worship", "Mia", "Engelbrecht"], ["kids", "Refilwe", "Tau"], ["youth", "Josh", "Pretorius"]],
};
/** How many members each scenario has besides its leads: inside its App band (`appActiveMembers`). */
const MEMBERS: Record<agent.DemoScenarioKey, number> = {
"heritage-parish": 48, "heritage-city": 520, "bold-youth": 1180, "bold-plant": 64,
"community-family": 210, "community-town": 160, "clean-modern": 610, "clean-campus": 2450,
};
const GIVEN = ["Aisha", "Andile", "Anele", "Bianca", "Busisiwe", "Carel", "Charlotte", "Craig", "Dineo", "Elias", "Emma", "Fatima", "Francois", "Gugu", "Hlengiwe", "Imran", "Isabel", "Jabu", "Jacques", "Karabo", "Keegan", "Lebo", "Lize", "Lungile", "Marco", "Mpho", "Nadia", "Neo", "Nicole", "Olwethu", "Pumla", "Riaan", "Sanele", "Shaun", "Simone", "Tarryn", "Thandeka", "Unathi", "Vusi", "Zanele"];
const FAMILY = ["Abrahams", "Bester", "Cloete", "Daniels", "Dlamini", "Erasmus", "February", "Gumede", "Hendricks", "Isaacs", "Joubert", "Kekana", "Lategan", "Maseko", "Moloi", "Ndlovu", "Ntuli", "Olivier", "Phiri", "Qwabe", "Roberts", "Snyman", "Tshabalala", "Uys", "Viljoen", "Williams", "Xaba", "Yende", "Zondo", "Van der Merwe"];
const slugOf = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "");
/**
* A UUID worked out from text (FNV-1a over 128 bits, shaped as version 5), so a demo person's id
* is the same in every product and on every load, without Node's crypto (it runs in browsers too).
*/
export function demoId(text: string): string {
let h = 0x6c62272e07bb014262b821756295c58dn;
const prime = 0x0000000001000000000000000000013bn;
const mask = (1n << 128n) - 1n;
for (const byte of new TextEncoder().encode(`crosscode-demo:${text}`)) h = ((h ^ BigInt(byte)) * prime) & mask;
const hex = h.toString(16).padStart(32, "0").split("");
hex[12] = "5";
hex[16] = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);
const s = hex.join("");
return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
}
function person(scenario: agent.DemoScenarioKey, part: DemoPart, givenName: string, familyName: string, email: string, campus: string | null): DemoPerson {
return { id: demoId(`${scenario}:${email}`), name: `${givenName} ${familyName}`, givenName, familyName, email, part, campus };
}
/** Everyone in a scenario: the leads first, then the members (deterministic: the same every time). */
export function demoPeople(scenario: agent.DemoScenarioKey): DemoPerson[] {
const church = demoChurch(scenario);
const campuses = church.profile.campuses.map((c) => c.slug);
const campusFor = (n: number) => (campuses.length ? campuses[n % campuses.length]! : null);
const seen = new Set<string>();
const out: DemoPerson[] = [];
LEADS[scenario].forEach(([part, given, family], n) => {
const email = `${slugOf(given)}.${slugOf(family)}.${church.slug}@${DEMO_EMAIL_DOMAIN}`;
// One person can have two parts (the pastor who writes the devotionals): one account.
const existing = out.find((p) => p.email === email);
if (existing) return;
seen.add(email);
out.push(person(scenario, part, given, family, email, campusFor(n)));
});
for (let n = 0; n < MEMBERS[scenario]; n++) {
const given = GIVEN[n % GIVEN.length]!;
const family = FAMILY[Math.floor(n / GIVEN.length) % FAMILY.length]!;
const email = `${slugOf(given)}.${slugOf(family)}.${n + 1}.${church.slug}@${DEMO_EMAIL_DOMAIN}`;
if (seen.has(email)) continue;
seen.add(email);
out.push(person(scenario, "member", given, family, email, campusFor(n)));
}
return out;
}
/** The parts each lead plays (a person may have two: the pastor who writes the devotionals). */
export function demoParts(scenario: agent.DemoScenarioKey): Map<string, DemoPart[]> {
const church = demoChurch(scenario);
const parts = new Map<string, DemoPart[]>();
for (const [part, given, family] of LEADS[scenario]) {
const email = `${slugOf(given)}.${slugOf(family)}.${church.slug}@${DEMO_EMAIL_DOMAIN}`;
parts.set(email, [...(parts.get(email) ?? []), part]);
}
return parts;
}
/** Whether an address belongs to a demo person (any scenario). */
export const isDemoAddress = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
/** The scenarios in the contracts' order. */
export const DEMO_SCENARIO_KEYS = agent.DEMO_SCENARIO_KEYS;
+77
View File
@@ -0,0 +1,77 @@
import { agent, churchObjectSchema, DEMO_EMAIL_DOMAIN, hub } from "@crosscode/contracts";
import { DEMO_CHURCHES, demoChurch, demoIconSvg, demoId, demoLogoSvg, demoParts, demoPeople } from "../src";
describe("demo churches", () => {
it("has one per scenario, with unique names, slugs and shapes the profile accepts", () => {
expect(DEMO_CHURCHES.map((c) => c.scenario)).toEqual([...agent.DEMO_SCENARIO_KEYS]);
expect(new Set(DEMO_CHURCHES.map((c) => c.slug)).size).toBe(8);
expect(new Set(DEMO_CHURCHES.map((c) => c.profile.name)).size).toBe(8);
for (const c of DEMO_CHURCHES) {
const { colours, style, contact, ...rest } = c.profile;
const profile = { ...rest, branding: { logoUrl: null, iconUrl: null, colours, style }, contact: { ...contact, phone: null, whatsapp: null } };
const check = churchObjectSchema.omit({ schema: true, customerId: true, updatedAt: true, links: true }).safeParse(profile);
expect(check.success ? [] : check.error.issues).toEqual([]);
expect(contact.email!.endsWith(`@${DEMO_EMAIL_DOMAIN}`)).toBe(true);
for (const s of c.profile.social) expect(s.url.startsWith("https://example.com/")).toBe(true);
}
});
it("matches the contracts' scenario (church name, campuses, language)", () => {
for (const s of agent.DEMO_SCENARIOS) {
const c = demoChurch(s.key);
expect(c.profile.name.startsWith(s.church)).toBe(true);
expect(Math.max(1, c.profile.campuses.length)).toBe(s.campuses);
expect(c.profile.locale.startsWith(s.language)).toBe(true);
}
});
});
describe("demo people", () => {
it("are at example.com, unique, with ids that stay the same", () => {
for (const key of agent.DEMO_SCENARIO_KEYS) {
const people = demoPeople(key);
expect(new Set(people.map((p) => p.email)).size).toBe(people.length);
expect(new Set(people.map((p) => p.id)).size).toBe(people.length);
for (const p of people) expect(p.email.endsWith(`@${DEMO_EMAIL_DOMAIN}`)).toBe(true);
expect(demoPeople(key).map((p) => p.id)).toEqual(people.map((p) => p.id));
}
});
it("put the App in the scenario's band", () => {
for (const s of agent.DEMO_SCENARIOS) expect(hub.activeMemberBand(demoPeople(s.key).length)).toBe(s.appActiveMembers);
});
it("have a pastor and a prayer coordinator; a person with two parts has one account", () => {
for (const key of agent.DEMO_SCENARIO_KEYS) {
const people = demoPeople(key);
expect(people.filter((p) => p.part === "pastor")).toHaveLength(1);
expect(people.filter((p) => p.part === "prayer-coordinator")).toHaveLength(1);
}
const plant = demoParts("bold-plant");
expect([...plant.values()].some((parts) => parts.includes("pastor") && parts.includes("devotional-writer"))).toBe(true);
});
it("spread a multi-campus church's members over its campuses", () => {
const campuses = new Set(demoPeople("clean-campus").map((p) => p.campus));
expect(campuses).toEqual(new Set(["stellenbosch", "paarl", "somerset-west"]));
expect(new Set(demoPeople("community-family").map((p) => p.campus))).toEqual(new Set([null]));
});
it("demoId is a stable version-5 UUID", () => {
expect(demoId("a")).toBe(demoId("a"));
expect(demoId("a")).not.toBe(demoId("b"));
expect(demoId("a")).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
});
});
describe("logos", () => {
it("are SVG in the church's colour, with its name", () => {
for (const c of DEMO_CHURCHES) {
const icon = demoIconSvg(c.scenario);
const logo = demoLogoSvg(c.scenario);
expect(icon.startsWith("<svg")).toBe(true);
expect(icon).toContain(c.profile.colours.primary);
expect(logo).toContain(c.profile.name.replace(/'/g, "&apos;"));
}
});
});
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"types": ["node", "jest"]
},
"include": ["src", "tests", "tsup.config.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from "tsup";
// CommonJS for the Events backend, ESM for the Next.js apps, types for both (as contracts).
export default defineConfig({
entry: ["src/index.ts"],
format: ["cjs", "esm"],
dts: true,
sourcemap: true,
clean: true,
target: "es2022",
external: ["@crosscode/contracts"],
outExtension: ({ format }) => ({ js: format === "esm" ? ".mjs" : ".js" }),
});
+53 -2
View File
@@ -16,6 +16,11 @@ crosscode demo <church> website --profile <profile>
bold-plant, community-family, community-town, bold-plant, community-family, community-town,
clean-modern, clean-campus); a backup is taken clean-modern, clean-campus); a backup is taken
first; the church's profile, settings and admins stay first; the church's profile, settings and admins stay
crosscode demo <church> accounts --profile <scenario> [--scenario <scenario>]
a demo scenario's church (profile, logo, icon) and
people in Accounts (the eight scenarios, as the
Website's profiles); a backup is taken first;
real people and admins stay
crosscode env <church> <product> the product's .env values (secrets hidden) crosscode env <church> <product> the product's .env values (secrets hidden)
crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart] crosscode env <church> <product> [--file backend/.env] --set NAME=value … [--unset NAME …] [--restart]
change values (a copy is kept; never secrets or change values (a copy is kept; never secrets or
@@ -91,24 +96,41 @@ cmd_restart() {
DEMO_PROFILES="small events ministry multicampus" DEMO_PROFILES="small events ministry multicampus"
# The Website's (contracts WEBSITE_DEMO_PROFILES): two per template. # The Website's (contracts WEBSITE_DEMO_PROFILES): two per template.
WEBSITE_DEMO_PROFILES="heritage-parish heritage-city bold-youth bold-plant community-family community-town clean-modern clean-campus" WEBSITE_DEMO_PROFILES="heritage-parish heritage-city bold-youth bold-plant community-family community-town clean-modern clean-campus"
# The demo scenarios (contracts agent.DEMO_SCENARIO_KEYS, 1.21.0): one per Website profile. Accounts'
# profiles are the scenarios themselves.
DEMO_SCENARIOS="$WEBSITE_DEMO_PROFILES"
# Replaces Events' data with a demo set (apps/events/backend/scripts/set-demo.js), as the site's # Replaces Events' data with a demo set (apps/events/backend/scripts/set-demo.js), as the site's
# user (its .env is readable only by that user). The Hub sends it only for installs marked as demo # user (its .env is readable only by that user). The Hub sends it only for installs marked as demo
# sites. Afterwards Events is reloaded: the demo switches campuses on or off. # sites. Afterwards Events is reloaded: the demo switches campuses on or off.
# `crosscode demo <church> website --profile <p>`: the Website's content instead (cmd_demo_website). # `crosscode demo <church> website --profile <p>`: the Website's content instead (cmd_demo_website).
# `crosscode demo <church> accounts --profile <scenario>`: a scenario's church and people (cmd_demo_accounts).
# `--scenario <s>` (agent 1.7.0): part of loading that scenario; the profile must be the scenario's.
cmd_demo() { cmd_demo() {
local church="" product="events" profile="" email="" dir user app local church="" product="events" profile="" email="" scenario="" dir user app
while [ $# -gt 0 ]; do while [ $# -gt 0 ]; do
case "$1" in case "$1" in
--profile) [ $# -ge 2 ] || die "--profile needs a value."; profile="$2"; shift 2 ;; --profile) [ $# -ge 2 ] || die "--profile needs a value."; profile="$2"; shift 2 ;;
--admin-email) [ $# -ge 2 ] || die "--admin-email needs a value."; email="$2"; shift 2 ;; --admin-email) [ $# -ge 2 ] || die "--admin-email needs a value."; email="$2"; shift 2 ;;
--scenario) [ $# -ge 2 ] || die "--scenario needs a value."; scenario="$2"; shift 2 ;;
-h|--help) manage_usage; return 0 ;; -h|--help) manage_usage; return 0 ;;
-*) die "Unknown option $1 (crosscode help demo)." ;; -*) die "Unknown option $1 (crosscode help demo)." ;;
events|website) [ -n "$church" ] || die "Name the church first (crosscode demo hope website …)."; product="$1"; shift ;; events|website|accounts) [ -n "$church" ] || die "Name the church first (crosscode demo hope website …)."; product="$1"; shift ;;
*) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;; *) [ -z "$church" ] || die "One church at a time."; church="$1"; shift ;;
esac esac
done done
[ -n "$church" ] || die "Name the church." [ -n "$church" ] || die "Name the church."
if [ -n "$scenario" ]; then
[[ " $DEMO_SCENARIOS " == *" $scenario "* ]] || die "--scenario: one of $DEMO_SCENARIOS."
# Every product loads the profile named after the scenario (contracts DEMO_SCENARIOS).
[ "$profile" = "$scenario" ] || die "--scenario $scenario loads the $scenario profile in $product, not $profile."
fi
if [ "$product" = accounts ]; then
[[ " $DEMO_SCENARIOS " == *" $profile "* ]] || die "--profile: one of $DEMO_SCENARIOS."
[ -z "$email" ] || die "--admin-email: Accounts' demo keeps every admin."
cmd_demo_accounts "$church" "$profile"
return
fi
if [ "$product" = website ]; then if [ "$product" = website ]; then
[[ " $WEBSITE_DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $WEBSITE_DEMO_PROFILES." [[ " $WEBSITE_DEMO_PROFILES " == *" $profile "* ]] || die "--profile: one of $WEBSITE_DEMO_PROFILES."
[ -z "$email" ] || die "--admin-email: the Website's demo keeps every admin." [ -z "$email" ] || die "--admin-email: the Website's demo keeps every admin."
@@ -144,6 +166,35 @@ cmd_demo() {
die "Events didn't answer after the reload (sudo -u $user pm2 logs)." die "Events didn't answer after the reload (sudo -u $user pm2 logs)."
} }
# Accounts' part of a demo scenario (Accounts 1.9.0+, backend/scripts/demo.ts): the scenario's
# church profile (with its logo and icon) and its people; real people and admins stay. Backup first;
# Accounts tells the linked products the church changed. Loaded before the other products'.
cmd_demo_accounts() {
local church="$1" profile="$2" dir user app
require_root
load_church "$church"
church_has_product accounts || die "$church has no Accounts."
# shellcheck source=/dev/null
source "$CROSSCODE_HOME/products/accounts.sh"
dir="$(pvar accounts DIR)"
user="$(pvar accounts USER)"
app="$(accounts_app "$dir")"
[ -f "$app/backend/scripts/demo.ts" ] || die "This release of Accounts ($(checkout_ref "$dir" accounts)) has no demo scenarios (1.9.0 or later has)."
step "Accounts: backup first"
accounts_backup "$dir" "$user" || die "The backup failed, so the demo wasn't loaded."
step "Accounts: demo scenario ($profile)"
run_as "$user" "$app/backend" npm run --silent demo -- --profile "$profile" --force ||
die "The demo wasn't loaded (see above). If it got as far as changing anything, the backup from just now has the data from before."
step "Accounts: reloading PM2"
accounts_reload "$dir" "$user"
step "Accounts: waiting for it to answer"
wait_for_version "$(accounts_health_url)" "$(accounts_expected_version "$dir")" 60 ||
die "Accounts didn't answer after the reload (sudo -u $user pm2 logs)."
}
# The Website's demo (Website 1.3.0+, backend/src/demo/seeds.ts): its content replaced with one of # The Website's demo (Website 1.3.0+, backend/src/demo/seeds.ts): its content replaced with one of
# the eight demo churches, keeping the church's profile, the site settings and the admins. Backup # the eight demo churches, keeping the church's profile, the site settings and the admins. Backup
# first; then reloaded, so nothing cached from before is shown. # first; then reloaded, so nothing cached from before is shown.
+4 -3
View File
@@ -17,10 +17,11 @@ accounts_expected_version() {
node -p 'require(process.argv[1]).version' "$(accounts_app "$1")/backend/package.json" 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). # The shared packages Accounts is built with (contracts, auth-client for its tests, ui for its pages,
# 1.9.0: demo for the demo scenarios).
accounts_shared_packages() { accounts_shared_packages() {
local p local p
for p in packages/contracts packages/ui packages/auth-client; do for p in packages/contracts packages/ui packages/auth-client packages/demo; do
[ -f "$1/$p/package.json" ] && printf '%s\n' "$p" [ -f "$1/$p/package.json" ] && printf '%s\n' "$p"
done done
} }
@@ -54,7 +55,7 @@ accounts_migrate() {
accounts_build() { accounts_build() {
local p local p
for p in packages/contracts packages/auth-client; do for p in packages/contracts packages/auth-client packages/demo; do
[ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1 [ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1
done done
run_as "$2" "$(accounts_app "$1")/backend" npm run build && run_as "$2" "$(accounts_app "$1")/backend" npm run build &&
+48 -1
View File
@@ -19,6 +19,15 @@ setup() {
touch "$TMP/sites/hope/events/apps/events/backend/scripts/set-demo.js" touch "$TMP/sites/hope/events/apps/events/backend/scripts/set-demo.js"
mkdir -p "$TMP/sites/hope/website/apps/website/backend/src/demo" mkdir -p "$TMP/sites/hope/website/apps/website/backend/src/demo"
touch "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts" touch "$TMP/sites/hope/website/apps/website/backend/src/demo/seeds.ts"
mkdir -p "$TMP/sites/hope/accounts/apps/accounts/backend/scripts"
touch "$TMP/sites/hope/accounts/apps/accounts/backend/scripts/demo.ts"
cat > "$CROSSCODE_HOME/products/accounts.sh" <<EOF3
accounts_app() { printf '%s/apps/accounts' "\$1"; }
accounts_backup() { echo "backup \$2" >> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; }
accounts_reload() { echo "reload \$2" >> "$CALLS"; }
accounts_health_url() { echo http://127.0.0.1:5200/api/health; }
accounts_expected_version() { echo 1.9.0; }
EOF3
cat > "$CROSSCODE_HOME/products/website.sh" <<EOF2 cat > "$CROSSCODE_HOME/products/website.sh" <<EOF2
website_app() { printf '%s/apps/website' "\$1"; } website_app() { printf '%s/apps/website' "\$1"; }
website_backup() { echo "backup \$2" >> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; } website_backup() { echo "backup \$2" >> "$CALLS"; [ -z "\${FAIL_BACKUP:-}" ]; }
@@ -35,7 +44,7 @@ events_expected_version() { echo 2.4.1; }
EOF EOF
require_root() { :; } require_root() { :; }
load_church() { [ "$1" = hope ] || die "There's no church $1 here."; } load_church() { [ "$1" = hope ] || die "There's no church $1 here."; }
church_has_product() { [ "$1" = events ] || [ "$1" = website ]; } church_has_product() { [ "$1" = events ] || [ "$1" = website ] || [ "$1" = accounts ]; }
pvar() { case "$2" in DIR) echo "$TMP/sites/hope/$1" ;; USER) echo "cc-hope-$1" ;; esac; } pvar() { case "$2" in DIR) echo "$TMP/sites/hope/$1" ;; USER) echo "cc-hope-$1" ;; esac; }
checkout_ref() { echo "$2@1.0.0"; } checkout_ref() { echo "$2@1.0.0"; }
wait_for_version() { echo "wait $2" >> "$CALLS"; } wait_for_version() { echo "wait $2" >> "$CALLS"; }
@@ -114,3 +123,41 @@ wait 1.3.0" ]
[[ "$output" == *"no demo profiles"* ]] [[ "$output" == *"no demo profiles"* ]]
[ ! -s "$CALLS" ] [ ! -s "$CALLS" ]
} }
@test "accounts: backup, then the scenario's church and people as the site's user, then a reload" {
run cmd_demo hope accounts --profile community-family --scenario community-family
[ "$status" -eq 0 ]
[ "$(cat "$CALLS")" = "backup cc-hope-accounts
run cc-hope-accounts sites/hope/accounts/apps/accounts/backend npm run --silent demo -- --profile community-family --force
reload cc-hope-accounts
wait 1.9.0" ]
}
@test "accounts: only a scenario, no admin email, and only a release that has scenarios" {
run cmd_demo hope accounts --profile small
[ "$status" -eq 1 ]
[[ "$output" == *"clean-campus"* ]]
run cmd_demo hope accounts --profile bold-youth --admin-email jane@hope.test
[ "$status" -eq 1 ]
rm "$TMP/sites/hope/accounts/apps/accounts/backend/scripts/demo.ts"
run cmd_demo hope accounts --profile bold-youth
[ "$status" -eq 1 ]
[[ "$output" == *"no demo scenarios"* ]]
[ ! -s "$CALLS" ]
}
@test "--scenario: a known one, and the profile must be the scenario's" {
run cmd_demo hope website --profile bold-plant --scenario bold-youth
[ "$status" -eq 1 ]
[[ "$output" == *"loads the bold-youth profile"* ]]
run cmd_demo hope accounts --profile bold-youth --scenario nowhere
[ "$status" -eq 1 ]
run cmd_demo hope website --profile bold-youth --scenario bold-youth
[ "$status" -eq 0 ]
}
@test "a failed Accounts demo isn't followed by a reload" {
FAIL_SEED=1 run cmd_demo hope accounts --profile clean-modern
[ "$status" -eq 1 ]
[[ "$(cat "$CALLS")" != *"reload"* ]]
}