Events 3.3.0, Accounts 1.3.0, contracts 1.11.0: Accounts looks like Events, backups; sign-out and upload fixes

- Accounts: account and admin pages in Cross Events' layout (top bar, sidebar,
  a page per section, dark footer); quick links to the church's sites
  (GET /me/apps); nightly pg_dump backups with Admin -> Backups (run, keep,
  download, audited; heartbeat lastBackupAt); a fuller built-in privacy notice
  with headings and bullets; a fixed favicon. /backups/ ignored (anchored, so
  src/backups is kept).
- Contracts 1.11.0: people.removeDemo (only @example.com, never an admin).
- Events: uploads served from the folder they're saved in (a backend started
  outside backend/ answered 404 for a logo it had just saved); Branding checks
  the file loads before saving; logout waits for the sign-out call so Accounts
  signs out too; set-demo removes the last demo's people from Accounts.
Tests: Accounts 62 + e2e 8, Events 782, contracts 225; npm run check passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 11:19:57 +02:00
co-authored by Claude Opus 5.5
parent 8ee64bb9c9
commit 8856d6b35d
61 changed files with 1514 additions and 162 deletions
+58 -4
View File
@@ -1,12 +1,14 @@
/**
* Accounts' admin (`/api/v2/admin/…`, docs/ACCOUNTS-1.0-PLAN.md §8): people, sign-in settings,
* linked products, the church profile, privacy notices and deletions, email and WhatsApp, the
* linked products, the church profile, privacy notices and deletions, email and WhatsApp, backups,
* licence and the audit log. Admins only, signed in with 2FA; viewing a person is access-logged.
*/
import fs from 'node:fs';
import express, { type Request, type Response } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { ApiError, handle, limit, sendError } from '../http.js';
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
import { currentSession } from '../oidc/sessions.js';
@@ -16,7 +18,7 @@ import { church, updateProfile } from '../church/profile.js';
import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { approveDeletion, cancelDeletion } from '../privacy/deletion.js';
import { currentNotice, publish } from '../privacy/notice.js';
import { builtInNotice, currentNotice, publish } from '../privacy/notice.js';
import { licenceStatus } from '../hub/licence.js';
import { connect as connectHub } from '../hub/client.js';
import { productName } from '../oidc/clients.js';
@@ -140,7 +142,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
r.get('/notices', handle(async (req, res) => {
await admin(req, res);
const list = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'desc' } });
return { current: await currentNotice(ctx), items: list };
// 1.3.0: the built-in text too, so an admin can start a new version from it.
return { current: await currentNotice(ctx), builtIn: await builtInNotice(ctx), items: list };
}));
r.post('/notices', handle(async (req, res) => {
@@ -245,6 +248,57 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
return disconnectFrom(ctx, String(req.params.installId), me, req);
}));
// ─── Backups (1.3.0) ───────────────────────────────────────────────────────
r.get('/backups', handle(async (req, res) => {
await admin(req, res);
const items = await listBackups(ctx);
return {
items: items.map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })),
nightly: await ctx.settings.bool('backup_nightly', true),
retain: await retainCount(ctx),
lastError: await ctx.settings.get('backup_last_error'),
};
}));
r.post('/backups/run', limit(10, 60), handle(async (req, res) => {
const me = await admin(req, res);
let b;
try {
b = await runBackup(ctx);
} catch (e) {
throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`);
}
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_made', targetType: 'backup', targetId: b.filename, ip: clientIp(req) });
return { filename: b.filename, size: b.size, createdAt: b.createdAt };
}));
r.put('/backups/settings', handle(async (req, res) => {
const me = await admin(req, res);
const retain = Number(req.body?.retain);
if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' });
await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: req.body?.nightly === false ? 'false' : 'true' });
const deleted = await rotate(ctx);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly: req.body?.nightly !== false, deleted }, ip: clientIp(req) });
return { retain, nightly: req.body?.nightly !== false, deleted };
}));
// A download holds everyone's data: admins only, audited, never cached.
r.get('/backups/:file/download', async (req, res) => {
try {
const me = await admin(req, res);
const file = backupPath(ctx, String(req.params.file));
if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.');
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file), ip: clientIp(req) });
res.setHeader('Content-Type', 'application/gzip');
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`);
fs.createReadStream(file).pipe(res);
} catch (e) {
sendError(res, e);
}
});
// ─── Licence, audit ────────────────────────────────────────────────────────
r.get('/licence', handle(async (req, res) => {
@@ -0,0 +1,129 @@
/**
* Database backups (1.3.0, as Cross Events' Settings → Backups): a gzipped `pg_dump` into
* backend/backups/ every night at 02:00 and whenever an admin asks, kept on this server only.
* The `crosscode` script makes the same files before every deploy and uninstall
* (scripts/products/accounts.sh), so the admin's list shows both, newest first.
*
* Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last
* run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client).
*/
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import type { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
import type { Ctx } from '../context.js';
/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */
export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups');
/** The names this module and the crosscode script give a backup: accounts-YYYYMMDD-HHMMSS.sql.gz. */
export const BACKUP_FILE = /^accounts-\d{8}-\d{6}\.sql\.gz$/;
export const DEFAULT_RETAIN = 14;
const MAX_RETAIN = 365;
export type Backup = { filename: string; size: number; createdAt: Date };
/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */
export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise<void> };
const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR;
/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */
export const pgDump: Dumper = (databaseUrl) => {
const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] });
let stderr = '';
child.stderr.on('data', (d) => { stderr += String(d); });
const done = new Promise<void>((resolve, reject) => {
child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`)));
child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`))));
});
return { stdout: child.stdout, done };
};
const pad = (n: number) => String(n).padStart(2, '0');
/** accounts-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */
export function backupName(at: Date): string {
return `accounts-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`;
}
export async function retainCount(ctx: Ctx): Promise<number> {
const n = Number(await ctx.settings.get('backup_retain_count'));
return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN;
}
/** Every backup in the folder, newest first. */
export async function listBackups(ctx: Ctx): Promise<Backup[]> {
let names: string[];
try {
names = await fs.promises.readdir(dir(ctx));
} catch {
return [];
}
const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => {
const st = await fs.promises.stat(path.join(dir(ctx), filename));
return { filename, size: st.size, createdAt: st.mtime };
}));
return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename));
}
/** The newest backup's time, for the Hub heartbeat. */
export async function lastBackupAt(ctx: Ctx): Promise<Date | null> {
return (await listBackups(ctx))[0]?.createdAt ?? null;
}
/** The full path of a backup to download, or null if there's no such backup (or a bad name). */
export function backupPath(ctx: Ctx, filename: string): string | null {
if (!BACKUP_FILE.test(filename)) return null;
const p = path.join(dir(ctx), filename);
return fs.existsSync(p) ? p : null;
}
/** Deletes the oldest backups beyond the number kept. */
export async function rotate(ctx: Ctx): Promise<number> {
const old = (await listBackups(ctx)).slice(await retainCount(ctx));
await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {})));
return old.length;
}
/**
* Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would
* look like a real backup). Records the outcome for the admin page.
*/
export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise<Backup> {
const url = ctx.config.databaseUrl;
try {
if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.');
await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 });
// Two in the same second (the button pressed twice): the next free second's name.
const at = ctx.now().getTime();
let filename = backupName(new Date(at));
for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000));
const file = path.join(dir(ctx), filename);
const { stdout, done } = dumper(url);
// Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way,
// so a failed one's file is deleted after the last write, not before it.
const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]);
const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected');
if (failed) {
await fs.promises.unlink(file).catch(() => {});
throw failed.reason;
}
await rotate(ctx);
await ctx.settings.set('backup_last_error', null);
const st = await fs.promises.stat(file);
return { filename, size: st.size, createdAt: st.mtime };
} catch (e) {
await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600));
throw e;
}
}
/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */
export async function runBackupJob(ctx: Ctx) {
if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true };
const b = await runBackup(ctx);
return { filename: b.filename, size: b.size };
}
+2 -1
View File
@@ -10,6 +10,7 @@ import type { Ctx } from '../context.js';
import { hubPublicKey, verifyToken } from './licence.js';
import { keyPair, saveLinkedProducts } from '../links/store.js';
import { appVersion } from '../lib/version.js';
import { lastBackupAt } from '../backups/backups.js';
export const PROTOCOL_VERSION = 2;
const TIMEOUT_MS = 15000;
@@ -55,7 +56,7 @@ export async function health(ctx: Ctx) {
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
db,
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
lastBackupAt: null,
lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null,
disk: null,
errorsLast24h: null,
pendingMigrations: 0,
+3
View File
@@ -4,6 +4,7 @@
*/
import PgBoss from 'pg-boss';
import type { Ctx } from './context.js';
import { runBackupJob } from './backups/backups.js';
import { heartbeat } from './hub/client.js';
import { runDue } from './links/deliveries.js';
import { forgetOldRequests } from './links/requests.js';
@@ -17,6 +18,8 @@ export const JOBS: Job[] = [
{ name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) },
{ name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) },
{ name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) },
// 1.3.0: a database backup every night (Settings → Backups), as Cross Events.
{ name: 'backup', cron: '0 2 * * *', everyMs: 24 * 3600e3, run: (ctx) => runBackupJob(ctx) },
{ name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) },
{
name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3,
+6
View File
@@ -25,6 +25,10 @@ export type Config = {
/** Local testing only: linked products on http or private addresses. */
allowPrivateLinks: boolean;
jobsEnabled: boolean;
/** 1.3.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */
databaseUrl: string | null;
/** 1.3.0: where backups go; default backend/backups (tests use their own folder). */
backupDir: string | null;
};
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
@@ -72,5 +76,7 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
wawp: env.WAWP_ACCESS_TOKEN && env.WAWP_INSTANCE_ID ? { accessToken: env.WAWP_ACCESS_TOKEN, instanceId: env.WAWP_INSTANCE_ID } : null,
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
jobsEnabled: bool(env.JOBS_ENABLED, true),
databaseUrl: env.DATABASE_URL?.trim() || null,
backupDir: null,
};
}
+24 -1
View File
@@ -15,7 +15,7 @@ import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import type Provider from 'oidc-provider';
import {
ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
} from '@crosscode/contracts';
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
@@ -29,6 +29,10 @@ import { BUILT_IN_VERSION } from '../privacy/notice.js';
import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js';
import { turnOff } from '../accounts/twoFactor.js';
import { signOutEverywhere } from '../oidc/sessions.js';
import { anonymise } from '../privacy/deletion.js';
/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */
export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
export class RequestError extends Error {
constructor(message: string, public code: string, public status = 400) {
@@ -284,6 +288,25 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req);
return reply({ ok: true as const });
}
case 'people.removeDemo': {
// 1.3.0: a product's new demo data replaces the old; the old demo people's accounts go.
const kept: { sub: string; reason: 'not_demo' | 'admin' | 'unknown' }[] = [];
let removed = 0;
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: r.subs } }, select: { accountId: true } })).map((p) => p.accountId));
const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: [...known] } } })).map((a) => [a.id, a]));
for (const sub of new Set(r.subs)) {
const a = accounts.get(sub);
if (!a || a.status === 'deleted') { kept.push({ sub, reason: 'unknown' }); continue; }
if (!isDemoEmail(a.email)) { kept.push({ sub, reason: 'not_demo' }); continue; }
if (a.role === 'admin') { kept.push({ sub, reason: 'admin' }); continue; }
await signOutEverywhere(ctx, provider, a.id);
await anonymise(ctx, a.id);
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
removed++;
}
await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length });
return reply({ removed, kept });
}
case 'church.branding': {
const changed = await applyLook(ctx, r.church, r.overwrite);
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
+19
View File
@@ -16,6 +16,13 @@ import { currentNotice } from '../privacy/notice.js';
import { requestExport } from '../privacy/export.js';
import { requestDeletion } from '../privacy/deletion.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { linkedProducts } from '../links/store.js';
/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */
const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' };
const APP_BLURBS: Record<string, string> = { events: 'Your bookings, tickets and serving', website: 'The church\'s website', app: 'The church app on your phone' };
const OPEN_PATHS: Record<string, string> = { events: '/api/auth/signin?returnTo=%2Fdashboard' };
const appName = (product: string) => APP_NAMES[product] ?? product;
export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: number; noticeVersion: number }) {
return {
@@ -44,6 +51,18 @@ export function meRouter(ctx: Ctx, provider: Provider) {
r.get('/me', handle(async (req, res) => view(await signedIn(req, res))));
// 1.3.0: the church's sites and apps that sign in here, for the account page's quick links.
r.get('/me/apps', handle(async (req, res) => {
await signedIn(req, res);
const [links, listed] = await Promise.all([ctx.db.productLink.findMany({ orderBy: { connectedAt: 'asc' } }), linkedProducts(ctx)]);
return {
items: links.map((l) => {
const url = (listed.find((x) => x.installId === l.installId)?.url ?? l.url).replace(/\/+$/, '');
return { id: l.installId, product: l.product, name: appName(l.product), description: APP_BLURBS[l.product] ?? null, url: `${url}${OPEN_PATHS[l.product] ?? '/'}` };
}),
};
}));
r.put('/me', handle(async (req, res) => {
const s = await signedIn(req, res);
const name = req.body?.name !== undefined ? String(req.body.name).trim().replace(/\s+/g, ' ') : s.account.name;
+68 -7
View File
@@ -8,18 +8,79 @@ import { church } from '../church/profile.js';
export const BUILT_IN_VERSION = 1;
/**
* The built-in notice (1.3.0: in sections, as Cross Events' privacy policy, and saying what
* Accounts actually does). Plain text: a line starting "## " is a heading, "• " a bullet. Filled
* in from the church profile, so it follows the church's name and contact details.
*/
export async function builtInNotice(ctx: Ctx) {
const c = await church(ctx);
const contact = c.contact.email ? ` You can reach us at ${c.contact.email}.` : '';
const org = c.name;
const contact = [c.contact.email && `• Email: ${c.contact.email}`, c.contact.phone && `• Phone: ${c.contact.phone}`].filter(Boolean) as string[];
const keepBackups = (await ctx.settings.get('backup_retain_count')) || '14';
return {
version: BUILT_IN_VERSION,
title: `How ${c.name} looks after your information`,
title: `How ${org} looks after your information`,
body: [
`${c.name} keeps your name, email address and (if you give it) phone number so you can sign in to the church's websites and apps, and so we can contact you about what you've signed up for.`,
'We only send you news if you say yes, and you can change that at any time on your account page.',
'You can download everything we hold about you, or ask us to delete your account, from your account page. We keep a record of sign-ins to protect your account.',
`We don't sell or share your information. The services that store it for us are bound to keep it safe.${contact}`,
].join('\n\n'),
'## In short',
`• Your church account is how you sign in to ${org}'s websites and apps. It holds your name, email address and, if you give it, your mobile number.`,
'• Your password is never stored, only a scrambled form of it that can\'t be turned back. Two-step sign-in codes and recovery codes are protected the same way.',
'• It\'s kept on the church\'s own server, not shared with other churches, and never sold.',
'• The church\'s sites only get your name and contact details, when you sign in to them, and when you change them here.',
'• News comes only if you say yes, and you can change that at any time.',
'• On your account page you can download everything held about you, see your sign-ins, and delete your account.',
'',
'## 1. Who we are',
`${org} ("we", "us") is responsible for your personal information under the Protection of Personal Information Act (POPIA). This notice is about your church account: the sign-in shared by ${org}'s websites and apps. Each site may hold more about you for what you do there (for example the events site's bookings and tickets), and explains that in its own privacy notice.`,
'',
'## 2. What we keep',
'• Your details: name, email address (and whether you\'ve confirmed it), and your mobile number if you add it.',
'• Signing in: your password as a one-way hash, which two-step sign-in method you use, your authenticator app\'s key (encrypted), and your recovery codes (hashed). Codes sent by email or WhatsApp last a few minutes and are never kept in readable form.',
'• Security records: when you sign in, fail to, change your password, or turn two-step sign-in on or off, with the time, the IP address, the device type and which site it was for. These let you spot sign-ins you don\'t recognise and let us look into misuse.',
'• Your choices: whether you want news by email or WhatsApp, which version of this notice you accepted, and when you made each choice.',
'• Which of the church\'s sites you use: so a change to your name or email reaches them, and a deletion is passed on.',
'• If you\'re an admin: what you change in the admin pages, in an audit log. When an admin opens someone\'s details, that\'s recorded too.',
'',
'## 3. How we use it',
`• To sign you in, once, to all of ${org}'s sites and apps, and to sign you out of all of them when you sign out or ask to.`,
'• To send what signing in needs: email confirmation links, password reset links, sign-in codes, and security notices.',
'• To send church news, only if you said yes.',
'• To keep your account safe: locking it after too many wrong passwords, and asking admins for a second step.',
'',
'## 4. Who can see it',
`• The church's sites and apps you sign in to get your name, email address and mobile number (and whether they're confirmed), and nothing else from here. Each is listed by the church under Linked products, and only ${org}'s own sites can be linked.`,
`• ${org}'s Accounts admins can see your details and recent sign-ins to help you (for example to unlock your account). They can't see your password or codes.`,
'• Email is sent through the church\'s email provider, and WhatsApp messages through WAWP (wawp.net); they get only the message and where it goes.',
'• The software (Cross Code Accounts) is licensed from Cross Code. Every 15 minutes it sends Cross Code\'s licence server totals, such as how many accounts there are and how many use two-step sign-in, and technical health information. Never names, contact details or anything else about a person.',
'• Nobody else, unless South African law requires it. We don\'t sell or rent your information.',
'',
'## 5. Where it\'s kept, and for how long',
`• On ${org}'s server, in its own database, separate from every other church.`,
`• Your account and its sign-in history are kept while you have the account. A copy of your data that you ask to download is kept for 7 days. Sign-in codes stop working after a few minutes, and links to set or reset a password after at most 7 days.`,
`• The database is backed up every night onto the same server; the last ${keepBackups} backups are kept, then deleted. Backups are only used to put things back after a fault.`,
'• When your account is deleted, your name, contact details, password, codes and sign-in history are removed straight away, and are gone from the backups once those backups are deleted in turn.',
'',
'## 6. Cookies',
`Signing in uses a few cookies that are strictly necessary: they keep you signed in (for as long as "Keep me signed in" lasts, if you tick it) and protect each sign-in step. There are no tracking, advertising or analytics cookies, and these pages load nothing from other websites apart from the church's own logo.`,
'',
'## 7. Your rights',
'Under POPIA you may see the information we hold about you, have it corrected or deleted, withdraw consent (for example to news), object to direct marketing, and complain to the Information Regulator. On your account page you can:',
'• change your details and your news choices;',
'• download a copy of everything the church\'s sites hold about you;',
'• see your recent sign-ins, and sign out everywhere;',
`• delete your account. You're signed out at once; an admin confirms it, then each of the church's sites deletes what it holds (a site may wait until an event you're booked for is over).`,
'We answer requests within 30 days. The Information Regulator: www.inforeg.org.za, enquiries@inforeg.org.za.',
'',
'## 8. Children',
'Anyone under 18 should have a parent\'s or guardian\'s permission to make a church account.',
'',
'## 9. Changes to this notice',
'If this notice changes, you\'re asked to read the new version the next time you sign in.',
'',
'## 10. Contact us',
contact.length ? `To ask about your information or use your rights, contact ${org}:` : `To ask about your information or use your rights, contact ${org}'s office.`,
...contact,
].join('\n'),
publishedAt: null as Date | null,
};
}