import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import request from 'supertest'; import { bibleTranslation, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH } from '@crosscode/contracts'; import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing'; import { stats } from '../src/hub/client.js'; import { enqueue } from '../src/lib/outbox.js'; import { queueAnnouncements, queueDevotionals, sendOutbox } from '../src/messaging/send.js'; import { fetchMessaging, MESSAGING_KEY, savedMessaging } from '../src/messaging/settings.js'; import { sendReminders } from '../src/prayer/jobs.js'; import { ACCOUNTS_INSTALL_ID, CHURCH_SMTP, CHURCH_WAWP, cookieHeader, harness, LINK_SECRET, MEMBER, PASTOR, signInAs, type Harness, } from './support/harness.js'; const OTHER = '44444444-4444-4444-8444-444444444444'; const COORD = '55555555-5555-4555-8555-555555555555'; const ORIGIN = 'https://app.hope.test'; const SECRET = 'My brother Themba is in hospital after the accident'; async function setup() { const h = await harness() as Harness; const as = (cookies: Record) => ({ get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)), post: (path: string, body: object = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body), put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body), }); const thandi = as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' })); const pieter = as(await signInAs(h, { sub: OTHER, name: 'Pieter Botha', email: 'pieter@hope.test' })); const admin = as(await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['owner'] }, true)); // Each their own number (the stand-in Accounts gives everyone the same one). await h.db.member.update({ where: { id: MEMBER }, data: { phone: '+27821110001' } }); await h.db.member.update({ where: { id: OTHER }, data: { phone: '+27821110002' } }); await h.db.member.update({ where: { id: PASTOR }, data: { phone: '+27821110003' } }); return { h, thandi, pieter, admin, visitor: as({}) }; } const send = (h: Harness) => sendOutbox(h.ctx, { pauseMs: 0 }); const rows = (h: Harness, table: string) => [...(h.db.tables.get(table)?.values() ?? [])] as Record[]; const inAnHour = (h: Harness) => new Date(h.clock.now().getTime() + 3600e3).toISOString(); async function reminder(h: Harness, memberId: string, channel: 'email' | 'whatsapp' | 'both', key = 'r1') { const start = inAnHour(h); await enqueue(h.ctx, { memberId, kind: 'prayer-reminder', channel, dedupeKey: key, payload: { commitmentId: 'c1', date: '2026-12-01', start, end: new Date(Date.parse(start) + 3600e3).toISOString(), timezone: 'Africa/Johannesburg', prayedPath: '/prayer/prayed?token=abc' }, }); } describe('the church\'s email and WhatsApp settings (decision 4)', () => { it('takes them from Accounts with messaging.get, opens the sealed secrets, and keeps them encrypted', async () => { const { h } = await setup(); const s = await fetchMessaging(h.ctx); assert.deepEqual(h.fake.requests.at(-1), { type: 'messaging.get', actor: null }); assert.deepEqual(s.email, CHURCH_SMTP); assert.deepEqual(s.whatsapp, CHURCH_WAWP); const stored = String(rows(h, 'appSetting').find((r) => r.key === MESSAGING_KEY)!.value); assert.ok(!stored.includes('smtp-pass') && !stored.includes('wawp-token')); }); it('fetches them again when Accounts says they changed, and refuses an unsigned hint', async () => { const { h } = await setup(); await fetchMessaging(h.ctx); h.fake.messaging = { email: { ...CHURCH_SMTP, from: 'office@hope.test' }, whatsapp: null }; const body = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: h.clock.now().toISOString(), email: true, whatsapp: true }); const unsigned = await request(h.app).post(MESSAGING_CHANGED_PATH).set('Content-Type', 'application/json').send(body); assert.equal(unsigned.status, 404); const headers = signedHeaders(LINK_HEADERS, { senderId: ACCOUNTS_INSTALL_ID, secret: LINK_SECRET, rawBody: body, now: h.clock.now() }); const res = await request(h.app).post(MESSAGING_CHANGED_PATH).set(headers).set('Content-Type', 'application/json').send(body); assert.equal(res.status, 200); assert.deepEqual(res.body, { schema: IDENTITY_REQUEST_SCHEMA, ok: true }); await new Promise((r) => setTimeout(r, 20)); const saved = await savedMessaging(h.ctx); assert.equal(saved!.email!.from, 'office@hope.test'); assert.equal(saved!.whatsapp, null); }); it('keeps messages waiting while the church has neither set up, and keeps the last copy when Accounts is down', async () => { const { h } = await setup(); h.fake.messaging = { email: null, whatsapp: null }; await reminder(h, MEMBER, 'email'); const out = await send(h); assert.match(String((out as { skipped: string }).skipped), /aren't set up/); assert.equal(h.transport.emails.length, 0); h.fake.messaging = { email: CHURCH_SMTP, whatsapp: CHURCH_WAWP }; await fetchMessaging(h.ctx); h.fake.messaging = new Error('Accounts could not be reached'); await assert.rejects(fetchMessaging(h.ctx)); assert.equal((await send(h) as { sent: number }).sent, 1); assert.equal(h.transport.emails[0]!.to, 'thandi@hope.test'); }); }); describe('sending (§8)', () => { it('sends a prayer reminder on the commitment\'s channel, with the "I prayed" link and the church\'s settings', async () => { const { h, thandi } = await setup(); // 10:00 tomorrow, reminded an hour before. assert.equal((await thandi.post('/api/v1/me/prayer/commitments', { startDate: '2026-12-02', startMinute: 600, durationMinutes: 60, recurrence: 'once', reminder: 'hour1', channel: 'both' })).status, 201); h.clock.set('2026-12-02T07:00:00Z'); assert.equal((await sendReminders(h.ctx) as { queued: number }).queued, 1); await send(h); const [mail] = h.transport.emails; const [wa] = h.transport.whatsapps; assert.equal(mail!.to, 'thandi@hope.test'); assert.deepEqual(mail!.settings, CHURCH_SMTP); assert.match(mail!.subject, /10:00–11:00/); assert.match(mail!.text, /https:\/\/app\.hope\.test\/prayer\/prayed\?token=/); assert.equal(wa!.to, '+27821110001'); assert.match(wa!.text, /10:00–11:00/); assert.equal(rows(h, 'outboxMessage')[0]!.sentVia, 'email,whatsapp'); }); it('checks STOP before every WhatsApp: a reminder goes by email instead, never to WhatsApp', async () => { const { h } = await setup(); await h.db.member.update({ where: { id: MEMBER }, data: { whatsappOptedOut: true } }); await reminder(h, MEMBER, 'whatsapp'); await send(h); assert.equal(h.transport.whatsapps.length, 0); assert.equal(h.transport.emails.length, 1); const m = rows(h, 'outboxMessage')[0]!; assert.equal(m.sentVia, 'email'); assert.match(String(m.error), /STOP/); }); it('stops WhatsApp to a number anyone in the App opted out with', async () => { const { h } = await setup(); await h.db.member.update({ where: { id: OTHER }, data: { phone: '0821110001', whatsappOptedOut: true } }); await reminder(h, MEMBER, 'whatsapp'); await send(h); assert.equal(h.transport.whatsapps.length, 0); assert.equal(h.transport.emails.length, 1); }); it('tries a failed send again later, then gives up after five tries', async () => { const { h } = await setup(); await enqueue(h.ctx, { memberId: MEMBER, kind: 'request-update', channel: 'email', dedupeKey: 'u1', payload: { requestId: 'x', what: 'approved', path: '/me/requests' } }); h.transport.fail.email = 'connect ECONNREFUSED'; await send(h); let m = rows(h, 'outboxMessage')[0]!; assert.equal(m.attempts, 1); assert.equal(m.sentAt, null); assert.equal((await send(h) as { sent: number }).sent, 0, 'not again before its time'); for (let i = 0; i < 4; i++) { h.clock.add(40 * 60e3); await send(h); } m = rows(h, 'outboxMessage')[0]!; assert.equal(m.attempts, 5); assert.ok(m.failedAt); assert.match(String(m.error), /ECONNREFUSED/); }); it('never sends a reminder once its slot has started', async () => { const { h } = await setup(); await reminder(h, MEMBER, 'email'); h.clock.add(2 * 3600e3); await send(h); assert.equal(h.transport.emails.length, 0); assert.match(String(rows(h, 'outboxMessage')[0]!.error), /Too late/); }); it('sends request updates on the member\'s choice (or not at all), and never a prayer request\'s text', async () => { const { h, thandi } = await setup(); const coord = await signInAs(h, { sub: COORD, name: 'Lerato Dlamini', roles: ['prayer_coordinator'] }, true); await h.db.member.update({ where: { id: COORD }, data: { phone: '+27821110004' } }); assert.equal((await thandi.put('/api/v1/me/notifications', { requestUpdates: 'whatsapp' })).status, 200); const r = await thandi.post('/api/v1/me/requests', { text: SECRET, visibility: 'members' }); assert.equal(r.status, 201); await request(h.app).post(`/api/v1/admin/requests/${r.body.id}/approve`).set('Cookie', cookieHeader(coord)).set('Origin', ORIGIN).send({}); await send(h); const toThandi = h.transport.whatsapps.filter((w) => w.to === '+27821110001'); assert.equal(toThandi.length, 1); assert.match(toThandi[0]!.text, /approved/); const coordEmail = (await h.db.member.findUnique({ where: { id: COORD } }))!.email; assert.deepEqual(h.transport.emails.filter((e) => e.to === coordEmail).map((e) => e.subject), ['A prayer request waits for approval']); const everything = JSON.stringify([h.transport.emails, h.transport.whatsapps]); assert.ok(!everything.includes('Themba')); // Turned off: nothing more. await thandi.put('/api/v1/me/notifications', { requestUpdates: 'off' }); await request(h.app).post(`/api/v1/admin/requests/${r.body.id}/reply`).set('Cookie', cookieHeader(coord)).set('Origin', ORIGIN).send({ text: 'We are praying with you.' }); const before = h.transport.whatsapps.length + h.transport.emails.length; await send(h); assert.equal(h.transport.whatsapps.length + h.transport.emails.length, before); }); }); describe('announcements and devotionals (§5, §6)', () => { it('sends an announcement once, at its publish time, to members who turned announcements on and gave news consent', async () => { const { h, thandi, pieter } = await setup(); await thandi.put('/api/v1/me/notifications', { announcements: 'both' }); await pieter.put('/api/v1/me/notifications', { announcements: 'email' }); await h.db.member.update({ where: { id: MEMBER }, data: { newsEmail: true, newsWhatsApp: false } }); // Pieter has no news consent: nothing for him. const publishAt = new Date(h.clock.now().getTime() + 3600e3); await h.db.announcement.create({ data: { slug: 'carols', title: 'Carols by candlelight', body: 'Join us on **Sunday** at 19:00.', publishAt, sendEmail: true, sendWhatsApp: true } }); assert.equal((await queueAnnouncements(h.ctx) as { queued: number }).queued, 0, 'not before its publish time'); h.clock.add(3600e3); assert.equal((await queueAnnouncements(h.ctx) as { queued: number }).queued, 1); assert.equal((await queueAnnouncements(h.ctx) as { queued: number }).queued, 0, 'once'); await send(h); assert.equal(h.transport.emails.length, 1); assert.equal(h.transport.emails[0]!.to, 'thandi@hope.test'); assert.match(h.transport.emails[0]!.text, /Join us on Sunday at 19:00/); assert.match(h.transport.emails[0]!.text, /\/announcements\/carols/); assert.equal(h.transport.whatsapps.length, 0, 'no news consent on WhatsApp, and never by email instead'); }); it('sends today\'s devotional at the member\'s time, once a day, with the translation\'s notice', async () => { const { h, thandi } = await setup(); const offer = await thandi.get('/api/v1/me/notifications'); assert.equal(offer.body.offerDevotional, true); assert.equal((await thandi.post('/api/v1/me/notifications/devotional-offer', { choice: 'both' })).status, 200); await thandi.put('/api/v1/me/notifications', { devotionalTime: '09:00' }); assert.equal((await thandi.get('/api/v1/me/notifications')).body.offerDevotional, false); await h.db.devotional.create({ data: { source: 'crosscode', date: '2026-12-01', title: 'Light in the dark', reference: 'John 1:5', location: { book: 'JHN', chapter: 1, verses: [5, 5] }, translation: 'BSB', passageText: 'The Light shines in the darkness, and the darkness has not overcome it.', body: 'Text' } }); // 08:00 in Johannesburg: not yet. assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 0); h.clock.set('2026-12-01T07:05:00Z'); assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 1); assert.equal((await queueDevotionals(h.ctx) as { queued: number }).queued, 0, 'once a day'); await send(h); const notice = bibleTranslation('BSB').copyright; assert.match(h.transport.emails[0]!.text, /The Light shines in the darkness/); assert.ok(h.transport.emails[0]!.text.includes(notice)); assert.ok(h.transport.emails[0]!.html!.includes('John 1:5')); assert.ok(h.transport.whatsapps[0]!.text.includes(notice)); assert.match(h.transport.whatsapps[0]!.text, /\/devotional\/2026-12-01/); }); }); describe('what the App sends me', () => { it('starts with the defaults, and refuses WhatsApp without a verified number or after STOP', async () => { const { h, thandi } = await setup(); const me = await thandi.get('/api/v1/me/notifications'); assert.equal(me.status, 200); assert.equal(me.body.requestUpdates, 'email'); assert.equal(me.body.announcements, 'off'); assert.equal(me.body.devotional, 'off'); assert.equal(me.body.devotionalTime, '06:00'); assert.equal(me.body.channels.whatsapp.reach, 'ok'); await h.db.member.update({ where: { id: MEMBER }, data: { whatsappOptedOut: true } }); assert.equal((await thandi.put('/api/v1/me/notifications', { announcements: 'whatsapp' })).body.error.code, 'WHATSAPP_STOPPED'); await h.db.member.update({ where: { id: MEMBER }, data: { whatsappOptedOut: false, phone: null } }); assert.equal((await thandi.put('/api/v1/me/notifications', { devotional: 'both' })).body.error.code, 'NO_PHONE'); assert.equal((await thandi.put('/api/v1/me/notifications', { devotionalTime: '06:10' })).status, 400); assert.equal((await thandi.put('/api/v1/me/notifications', { devotional: 'email', devotionalTime: '05:30' })).body.devotionalTime, '05:30'); }); it('needs a sign-in', async () => { const { visitor } = await setup(); assert.equal((await visitor.get('/api/v1/me/notifications')).status, 401); }); it('keeps the news consent from Accounts, exports the choices and deletes them with the account', async () => { const { h, thandi } = await setup(); await thandi.put('/api/v1/me/notifications', { announcements: 'email' }); const call = (body: object) => request(h.app).post('/api/accounts/v1/events').set('x-test-signed', 'yes').set('Content-Type', 'application/json').send(JSON.stringify(body)); await call({ schema: 'crosscode.identity/1', type: 'user.updated', sub: MEMBER, occurredAt: h.clock.now().toISOString(), profile: { name: 'Thandi Mokoena', given_name: 'Thandi', family_name: 'Mokoena', email: 'thandi@hope.test', email_verified: true, phone_number: '+27821110001', phone_number_verified: true, news_consent: { email: true, whatsapp: false } } }); assert.equal((await h.db.member.findUnique({ where: { id: MEMBER } }))!.newsEmail, true); const exp = await call({ schema: 'crosscode.identity/1', type: 'user.export', sub: MEMBER, exportId: '77777777-7777-4777-8777-777777777777', occurredAt: h.clock.now().toISOString() }); assert.ok(exp.body.sections.some((s: { key: string }) => s.key === 'app_notifications')); await call({ schema: 'crosscode.identity/1', type: 'user.deleted', sub: MEMBER, occurredAt: h.clock.now().toISOString() }); assert.equal(rows(h, 'notificationSettings').length, 0); }); }); describe('Settings → Email and WhatsApp', () => { it('shows what the App sends from (never the secrets), and sends the admin a test', async () => { const { h, admin, thandi } = await setup(); assert.equal((await thandi.get('/api/v1/admin/messaging')).status, 403); assert.equal((await admin.post('/api/v1/admin/messaging/fetch')).status, 200); const s = await admin.get('/api/v1/admin/messaging'); assert.equal(s.status, 200); assert.equal(s.body.email.from, 'app@hope.test'); assert.equal(s.body.whatsapp.instanceId, 'HOPE1'); assert.equal(s.body.keptIn.product, 'accounts'); assert.ok(!JSON.stringify(s.body).includes('smtp-pass') && !JSON.stringify(s.body).includes('wawp-token')); const email = await admin.post('/api/v1/admin/messaging/test', { channel: 'email' }); assert.equal(email.body.sentTo, 'pastor@hope.test'); const wa = await admin.post('/api/v1/admin/messaging/test', { channel: 'whatsapp' }); assert.equal(wa.body.sentTo, '+27821110003'); await h.db.member.update({ where: { id: PASTOR }, data: { whatsappOptedOut: true } }); const stopped = await admin.post('/api/v1/admin/messaging/test', { channel: 'whatsapp' }); assert.equal(stopped.status, 502); assert.match(stopped.body.error.message, /STOP/); }); it('counts what was sent for the Hub\'s heartbeat', async () => { const { h } = await setup(); await reminder(h, MEMBER, 'both'); await reminder(h, OTHER, 'email', 'r2'); await send(h); const s = await stats(h.ctx); assert.deepEqual(s.messages, { email30d: 2, whatsapp30d: 1 }); }); });