Events: env template, church export, register with HUB_LICENCE_KEY

- apps/events/env.template.json (crosscode.env-template/1): every .env
  variable with its layer (server, defaults, install, generated).
- scripts/export-church.ts writes crosscode.church-export/1 (export-only
  references, no internal ids or secrets) for crosscode export.
- Installs made from the Hub register by themselves on first start when
  HUB_LICENCE_KEY is set (retries while the Hub is unreachable).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 12:06:01 +02:00
co-authored by Claude Opus 5.5
parent 90a98a4306
commit 350ab9f4e8
7 changed files with 378 additions and 2 deletions
@@ -0,0 +1,56 @@
// The church's data when it leaves (crosscode.church-export/1): plain terms, export-only
// references, no internal ids and no secrets.
jest.mock('../src/config/db', () => ({}));
import { buildExport } from '../src/services/churchExport';
const d = (s: string) => new Date(s);
const input = {
version: '2.3.0',
users: [
{ id: 'u-uuid-1', name: 'Thandi', email: 't@x.org', phoneNumber: '+27821234567', role: 'admin', createdAt: d('2026-01-01T08:00:00Z'), newsEmail: true, newsWhatsApp: false, password: '$2b$hash', tokenVersion: 3 },
{ id: 'u-uuid-2', name: 'Sipho', email: 's@x.org', phoneNumber: null, role: 'user', createdAt: d('2026-02-01T08:00:00Z'), newsEmail: false, newsWhatsApp: true },
],
events: [{
id: 'ev-uuid-1', title: 'Camp', description: null, startDate: d('2026-12-04T16:00:00Z'), endDate: d('2026-12-06T12:00:00Z'), location: 'Camp X', isActive: true, isHidden: false,
sessions: [{ id: 's-1', label: 'Friday', startsAt: d('2026-12-04T16:00:00Z'), endsAt: d('2026-12-04T21:00:00Z') }],
eventOptions: [{ id: 'opt-uuid-1', name: 'Camper', price: 600 }],
}],
registrations: [{
id: 'reg-uuid-1', eventId: 'ev-uuid-1', userId: 'u-uuid-2', status: 'paid', createdAt: d('2026-11-01T09:00:00Z'),
attendees: [{ id: 'att-1', name: 'Sipho', email: 's@x.org', eventOptionId: 'opt-uuid-1', ticket: { usages: [{ scannedAt: d('2026-12-04T16:30:00Z') }] } }],
formResponses: [{ answers: [{ fieldId: 'f-1', value: 'None' }] }],
}],
payments: [{ id: 'pay-1', registrationId: 'reg-uuid-1', amount: 600, method: 'card', status: 'completed', createdAt: d('2026-11-01T09:05:00Z'), externalId: 'YOCO-1' }],
usages: [{ id: 'use-1', scannedAt: d('2026-12-04T16:30:00Z'), ticket: { eventId: 'ev-uuid-1', userId: 'u-uuid-2', holderUserId: null, attendee: { name: 'Sipho' } } }],
slots: [{ id: 'slot-1', roleId: 'role-1', userId: 'u-uuid-1' }],
roles: [{ id: 'role-1', eventId: 'ev-uuid-1', name: 'Kitchen', startsAt: null, endsAt: null }],
settings: [{ key: 'org_name', value: 'Hope Church' }, { key: 'smtp_password', value: 'enc:secret' }, { key: 'hub_install_secret', value: 'x' }],
fields: [{ id: 'f-1', label: 'Dietary needs' }],
};
describe('church export', () => {
const out = buildExport(input, new Date('2026-11-20T12:00:00Z'));
test('uses export-only references that link up', () => {
expect(out.people.map(p => p.ref)).toEqual(['p1', 'p2']);
expect(out.events[0]).toMatchObject({ ref: 'e1', ticketTypes: [{ ref: 't1', priceCents: 60000 }], published: true });
expect(out.registrations[0]).toMatchObject({ ref: 'r1', eventRef: 'e1', personRef: 'p2', attendees: [{ ticketTypeRef: 't1', checkedInAt: '2026-12-04T16:30:00.000Z' }], answers: [{ question: 'Dietary needs', answer: 'None' }] });
expect(out.payments[0]).toMatchObject({ registrationRef: 'r1', amountCents: 60000, reference: 'YOCO-1' });
expect(out.checkIns[0]).toMatchObject({ eventRef: 'e1', personRef: 'p2', name: 'Sipho' });
expect(out.rosters[0]).toMatchObject({ eventRef: 'e1', role: 'Kitchen', personRef: 'p1' });
expect(out.church.name).toBe('Hope Church');
});
test('has no internal ids and no secrets', () => {
const text = JSON.stringify(out);
for (const secret of ['uuid', '$2b$hash', 'enc:secret', 'hub_install_secret', 'smtp_password', 'tokenVersion', 'password']) expect(text).not.toContain(secret);
const keys: string[] = [];
const walk = (v: unknown): void => {
if (Array.isArray(v)) v.forEach(walk);
else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) { keys.push(k); walk(x); }
};
walk(out);
expect(keys.filter(k => /^(id|.*Id|uuid|_id)$/.test(k))).toEqual([]);
});
});
@@ -0,0 +1,62 @@
// Installs made from the Hub register by themselves with HUB_LICENCE_KEY (AGENT-1.0-PLAN §7).
const mockSettings = new Map();
jest.mock('../src/config/db', () => ({
appSetting: {
findMany: jest.fn(async ({ where }) => [...mockSettings].filter(([key]) => where.key.in.includes(key)).map(([key, value]) => ({ key, value }))),
upsert: jest.fn(async ({ where, create }) => { mockSettings.set(where.key, create.value); }),
deleteMany: jest.fn(async ({ where }) => { mockSettings.delete(where.key); }),
},
}));
jest.mock('../src/hub/report', () => ({ APP_VERSION: '2.3.0', installInfo: async () => ({ name: 'Hope', url: 'https://events.hope.co.za', version: '2.3.0' }) }));
jest.mock('../src/hub/publicKey', () => ({ hubPublicKey: () => 'pem' }));
jest.mock('../src/hub/licence', () => ({ verifyToken: () => ({ installId: 'inst_1' }), clearLicenceCache: () => {} }));
const hub = require('../src/hub/client');
const reply = (status, body) => ({ ok: status < 400, status, json: async () => body });
const noSleep = async () => {};
describe('registering with HUB_LICENCE_KEY', () => {
let bodies;
beforeEach(() => {
mockSettings.clear();
bodies = [];
process.env.HUB_LICENCE_KEY = 'CEH-7K2M-9QXA-P4RT-WD8C';
process.env.HUB_ADMIN_NAME = 'Jane Admin';
process.env.HUB_ADMIN_EMAIL = 'jane@hope.co.za';
global.fetch = jest.fn(async (_url, opts) => {
bodies.push(JSON.parse(opts.body));
return reply(201, { installId: 'inst_1', installSecret: 's3cret', licence: 'hel1.x.y', heartbeatIntervalMinutes: 15 });
});
});
afterEach(() => {
delete global.fetch;
delete process.env.HUB_LICENCE_KEY;
delete process.env.HUB_ADMIN_NAME;
delete process.env.HUB_ADMIN_EMAIL;
});
test('registers once, with the admin contact, and stores the install', async () => {
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: true });
expect(bodies[0]).toMatchObject({ licenceKey: 'CEH-7K2M-9QXA-P4RT-WD8C', install: { adminContact: { name: 'Jane Admin', email: 'jane@hope.co.za' } } });
expect(mockSettings.get('hub_install_id')).toBe('inst_1');
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: false, reason: 'already' });
expect(global.fetch).toHaveBeenCalledTimes(1);
});
test('does nothing without the key', async () => {
delete process.env.HUB_LICENCE_KEY;
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: false, reason: 'no_key' });
expect(global.fetch).not.toHaveBeenCalled();
});
test('a refused key isn\'t tried again; an unreachable Hub is', async () => {
global.fetch = jest.fn(async () => reply(404, { code: 'LICENCE_NOT_FOUND', message: 'Unknown key' }));
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: false, reason: 'LICENCE_NOT_FOUND' });
expect(global.fetch).toHaveBeenCalledTimes(1);
global.fetch = jest.fn(async () => { throw new Error('ECONNREFUSED'); });
expect(await hub.connectFromEnv({ attempts: 3, sleep: noSleep })).toEqual({ connected: false, reason: 'unreachable' });
expect(global.fetch).toHaveBeenCalledTimes(3);
});
});