import { afterEach, describe, it } from 'node:test'; import assert from 'node:assert/strict'; import request from 'supertest'; import { DEVOTIONAL_CSV_TEMPLATE, DEVOTIONAL_SCHEMA, devotionalCsv, EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventFeedSchema } from '@crosscode/contracts'; import { stats } from '../src/hub/client.js'; import { nightlySync, syncCrosscode } from '../src/content/devotionals.js'; import { syncAll } from '../src/events/feed.js'; import { cookieHeader, harness, INSTALL_ID, MEMBER, signInAs, type Harness } from './support/harness.js'; const EDITOR = '55555555-5555-4555-8555-555555555555'; const WRITER = '66666666-6666-4666-8666-666666666666'; const EVENTS_INSTALL = '7b1c2d3e-4f50-4617-8829-3a4b5c6d7e8f'; const DAY = 864e5; const realFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = realFetch; }); async function setup(env: Record = {}) { const h = await harness({ env: { LINKS_ALLOW_PRIVATE: 'true', ...env } }) as Harness; const as = (cookies: Record) => ({ get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)), post: (path: string, body: object | string = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body), put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test').send(body), del: (path: string) => request(h.app).delete(path).set('Cookie', cookieHeader(cookies)).set('Origin', 'https://app.hope.test'), }); return { h, member: as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena' })), editor: as(await signInAs(h, { sub: EDITOR, name: 'Ruth', roles: ['content_admin'] }, true)), writer: as(await signInAs(h, { sub: WRITER, name: 'Pastor Sam', roles: ['devotional_writer'] }, true)), visitor: as({}), }; } // The clock starts on 1 December 2026, 08:00 in Johannesburg. const announcement = (over: object = {}) => ({ title: 'Family camp registrations open', body: 'Sign up **this week**.', ...over }); describe('announcements', () => { it('a Content admin publishes; visitors see public ones, members the members-only ones too', async () => { const { editor, member, visitor } = await setup(); assert.equal((await member.post('/api/v1/admin/announcements', announcement())).status, 403); assert.equal((await editor.post('/api/v1/admin/announcements', announcement())).status, 201); await editor.post('/api/v1/admin/announcements', announcement({ title: 'Leaders meeting', audience: 'members' })); await editor.post('/api/v1/admin/announcements', announcement({ title: 'Pinned notice', pinned: true })); const pub = await visitor.get('/api/v1/announcements'); assert.match(pub.headers['cache-control']!, /public/); assert.deepEqual(pub.body.announcements.map((a: { title: string }) => a.title), ['Pinned notice', 'Family camp registrations open']); const mine = await member.get('/api/v1/announcements'); assert.match(mine.headers['cache-control']!, /private/); assert.equal(mine.body.announcements.length, 3); const slug = mine.body.announcements.find((a: { title: string }) => a.title === 'Leaders meeting').slug; assert.equal((await visitor.get(`/api/v1/announcements/${slug}`)).status, 401); assert.equal((await member.get(`/api/v1/announcements/${slug}`)).body.announcement.membersOnly, true); }); it('keeps drafts and scheduled ones out until their time, and ended ones out after', async () => { const { h, editor, visitor } = await setup(); await editor.post('/api/v1/admin/announcements', announcement({ title: 'Draft', publishAt: null })); await editor.post('/api/v1/admin/announcements', announcement({ title: 'Later', publishAt: '2026-12-03T06:00:00Z' })); await editor.post('/api/v1/admin/announcements', announcement({ title: 'Short', endsAt: '2026-12-02T06:00:00Z' })); assert.deepEqual((await visitor.get('/api/v1/announcements')).body.announcements.map((a: { title: string }) => a.title), ['Short']); h.clock.add(3 * DAY); assert.deepEqual((await visitor.get('/api/v1/announcements')).body.announcements.map((a: { title: string }) => a.title), ['Later']); const list = (await editor.get('/api/v1/admin/announcements')).body.announcements; assert.deepEqual(Object.fromEntries(list.map((a: { title: string; state: string }) => [a.title, a.state])), { Draft: 'draft', Later: 'live', Short: 'ended' }); }); it('checks the button, the campus and the end', async () => { const { editor } = await setup(); const bad = await editor.post('/api/v1/admin/announcements', announcement({ buttonUrl: 'https://example.com' })); assert.equal(bad.body.error.fields.buttonLabel, 'A button needs both its words and its link.'); assert.equal((await editor.post('/api/v1/admin/announcements', announcement({ campus: 'north' }))).body.error.fields.campus, 'There\'s no such campus in the church profile.'); assert.equal((await editor.post('/api/v1/admin/announcements', announcement({ publishAt: '2026-12-05T06:00:00Z', endsAt: '2026-12-04T06:00:00Z' }))).status, 400); }); it('counts the last 30 days in the heartbeat, and is switched off with its module', async () => { const { h, editor, visitor } = await setup(); await editor.post('/api/v1/admin/announcements', announcement()); assert.equal((await stats(h.ctx)).announcements.last30d, 1); await h.ctx.settings.set('modules', JSON.stringify({ announcements: false })); assert.equal((await visitor.get('/api/v1/announcements')).body.error.code, 'MODULE_OFF'); }); }); // ── Devotionals ── const hubDay = (date: string, over: object = {}) => ({ schema: DEVOTIONAL_SCHEMA, id: `0000000${date.slice(-1)}-0000-4000-8000-00000000000${date.slice(-1)}`, source: 'crosscode', updatedAt: '2026-11-30T10:00:00.000Z', date, title: `Cross Code for ${date}`, body: 'Abide in him.', prayer: null, author: 'Cross Code', passage: { reference: 'John 15:1-5', location: { book: 'JHN', chapter: 15, verse: 1, endChapter: 15, endVerse: 5 }, translation: 'BSB', text: 'I am the true vine…' }, ...over, }); function stubHub(days: object[], from = '2026-12-01', to = '2026-12-14') { const calls: { url: string; auth: string | null }[] = []; globalThis.fetch = (async (url: string | URL, init?: RequestInit) => { calls.push({ url: String(url), auth: new Headers(init?.headers).get('authorization') }); return new Response(JSON.stringify({ schema: DEVOTIONAL_SCHEMA, from, to, devotionals: days, generatedAt: '2026-12-01T00:00:00.000Z' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); }) as typeof fetch; return calls; } describe('devotionals', () => { it('fetches Cross Code\'s 2 weeks from the Hub with the licence, today first in the church\'s timezone', async () => { const { h, visitor } = await setup(); await h.ctx.settings.set('hub_licence', 'licence-token'); const calls = stubHub([hubDay('2026-12-01'), hubDay('2026-12-02')]); assert.deepEqual(await syncCrosscode(h.ctx), { from: '2026-12-01', to: '2026-12-14', saved: 2, removed: 0 }); const hubCall = calls.find((c) => c.url.includes('/api/v2/devotionals'))!; assert.equal(hubCall.url, 'https://hub.crosscode.co.za/api/v2/devotionals?from=2026-12-01'); assert.equal(hubCall.auth, 'Bearer licence-token'); const today = (await visitor.get('/api/v1/devotionals/today')).body.devotional; assert.equal(today.title, 'Cross Code for 2026-12-01'); assert.equal(today.passage.translationName, 'Berean Standard Bible'); assert.match(today.passage.copyright, /Berean/); assert.equal(today.passage.youVersionUrl, 'https://www.bible.com/bible/3034/JHN.15.1-5.BSB'); // Tomorrow's isn't shown before its day. assert.equal((await visitor.get('/api/v1/devotionals/2026-12-02')).status, 404); }); it('replaces exactly the fetched days and keeps earlier ones when the Hub is down', async () => { const { h, visitor } = await setup(); await h.ctx.settings.set('hub_licence', 'licence-token'); stubHub([hubDay('2026-12-01'), hubDay('2026-12-02'), hubDay('2026-12-03')]); await syncCrosscode(h.ctx); h.clock.add(DAY); // The Hub removed 3 December: it goes; 1 December stays for the archive. stubHub([hubDay('2026-12-02', { title: 'Changed in the Hub' })], '2026-12-02', '2026-12-15'); assert.deepEqual(await syncCrosscode(h.ctx), { from: '2026-12-02', to: '2026-12-15', saved: 1, removed: 1 }); assert.equal((await visitor.get('/api/v1/devotionals/today')).body.devotional.title, 'Changed in the Hub'); assert.deepEqual((await visitor.get('/api/v1/devotionals?month=2026-12')).body.days.map((d: { date: string }) => d.date), ['2026-12-02', '2026-12-01']); globalThis.fetch = (async () => { throw new Error('connect ECONNREFUSED'); }) as typeof fetch; h.clock.add(DAY); await assert.rejects(syncCrosscode(h.ctx), /can't be reached/); // Nothing for 3 December, so today shows the most recent one. const today = (await visitor.get('/api/v1/devotionals/today')).body.devotional; assert.deepEqual([today.date, today.today], ['2026-12-02', false]); }); it('never keeps a translation that isn\'t free, nor more than 2 weeks, whatever the Hub sends', async () => { const { h } = await setup(); await h.ctx.settings.set('hub_licence', 'licence-token'); stubHub([hubDay('2026-12-01', { passage: { ...hubDay('2026-12-01').passage, translation: 'NIV' } }), hubDay('2026-12-02')], '2026-12-01', '2027-02-28'); const out = await syncCrosscode(h.ctx); assert.deepEqual([out.to, out.saved], ['2026-12-14', 1]); }); it('skips the nightly fetch when the church shows its own', async () => { const { h, writer } = await setup(); await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); assert.deepEqual(await nightlySync(h.ctx), { skipped: 'The church shows its own devotionals.' }); }); it('a Devotional writer writes the church\'s own, in the free translations only', async () => { const { h, writer, visitor, member } = await setup(); await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); const own = { date: '2026-12-01', title: 'Rest', reference: 'Matt 11:28-30', translation: 'KJV', passageText: 'Come unto me…', body: 'Jesus offers rest.', membersOnly: false }; assert.equal((await member.post('/api/v1/admin/devotionals', own)).status, 403); assert.equal((await writer.post('/api/v1/admin/devotionals', { ...own, translation: 'NIV' })).body.error.fields.translation, 'Use KJV or BSB: the others need their publisher\'s permission.'); assert.equal((await writer.post('/api/v1/admin/devotionals', { ...own, reference: 'Hezekiah 4:1' })).body.error.code, 'VALIDATION'); const long = await writer.post('/api/v1/admin/devotionals', { ...own, date: '2026-12-02', reference: 'Psalm 119:1-40' }); assert.match(long.body.warnings[0], /40 verses/); assert.equal((await writer.post('/api/v1/admin/devotionals', own)).status, 201); assert.equal((await writer.post('/api/v1/admin/devotionals', own)).body.error.code, 'DATE_TAKEN'); const today = (await visitor.get('/api/v1/devotionals/today')).body.devotional; assert.deepEqual([today.source, today.passage.reference, today.passage.youVersionUrl], ['church', 'Matt 11:28-30', 'https://www.bible.com/bible/1/MAT.11.28-30.KJV']); void h; }); it('keeps a members-only devotional from visitors', async () => { const { writer, visitor, member } = await setup(); await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); await writer.post('/api/v1/admin/devotionals', { date: '2026-12-01', title: 'For us', reference: 'John 3:16', translation: 'BSB', passageText: 'For God so loved…', body: 'Body', membersOnly: true }); assert.equal((await visitor.get('/api/v1/devotionals/today')).body.devotional, null); assert.equal((await visitor.get('/api/v1/devotionals/2026-12-01')).status, 401); assert.equal((await member.get('/api/v1/devotionals/today')).body.devotional.title, 'For us'); }); it('imports a CSV: a preview changes nothing; then the valid rows, days already filled replaced or skipped', async () => { const { h, writer } = await setup(); const csv = devotionalCsv([ { date: '2026-12-05', title: 'One', passage: 'John 1:1', translation: 'KJV', passage_text: 'In the beginning…', body: 'Body one' }, { date: '2026-12-06', title: 'Two', passage: 'John 1:2', translation: 'NIV', passage_text: 'The same…', body: 'Body two' }, { date: '2026-12-07', title: 'Three', passage: 'John 1:3', translation: 'BSB', passage_text: 'Through him…', body: 'Body three' }, ]); await writer.post('/api/v1/admin/devotionals', { date: '2026-12-07', title: 'Old', reference: 'John 1:3', translation: 'BSB', passageText: 'x', body: 'y' }); const post = (q: string) => writer.post(`/api/v1/admin/devotionals/import${q}`, csv).set('Content-Type', 'text/csv'); const preview = (await post('')).body; assert.deepEqual([preview.valid, preview.imported, preview.rows[1].errors.length > 0, preview.rows[2].taken], [2, 0, true, true]); assert.equal(await h.db.devotional.count({ where: { source: 'church' } }), 1); const skipped = (await post('?preview=false&taken=skip')).body; assert.deepEqual([skipped.imported, skipped.skipped], [1, 1]); const replaced = (await post('?preview=false&taken=replace')).body; // 5 December was imported by the run before, so both valid rows replace a day now. assert.deepEqual([replaced.replaced, replaced.imported], [2, 0]); assert.equal((await h.db.devotional.findUnique({ where: { source_date: { source: 'church', date: '2026-12-07' } } }))!.title, 'Three'); assert.equal((await writer.get('/api/v1/admin/devotionals/template')).text, DEVOTIONAL_CSV_TEMPLATE); }); it('lists every quoted translation\'s notice for the Acknowledgements page', async () => { const { writer, visitor } = await setup(); await writer.post('/api/v1/admin/devotionals', { date: '2026-12-01', title: 'A', reference: 'John 3:16', translation: 'BSB', passageText: 'x', body: 'y' }); const t = (await visitor.get('/api/v1/devotionals/acknowledgements')).body.translations; assert.deepEqual(t.map((x: { id: string }) => x.id), ['BSB']); assert.ok(t[0].acknowledgement.length > 20); }); }); // ── Events ── const event = (over: object = {}) => ({ title: 'Family camp', date: '2026-12-12', startTime: '09:00', endDate: '2026-12-13', endTime: '15:00', location: 'Magaliesberg', description: 'Two days away.', ...over }); describe('events', () => { it('a Content admin adds simple events in the church\'s timezone; drafts stay out', async () => { const { editor, visitor, member } = await setup(); assert.equal((await member.post('/api/v1/admin/events', event())).status, 403); const created = await editor.post('/api/v1/admin/events', event()); assert.equal(created.status, 201); assert.equal(created.body.slug, 'family-camp-2026-12-12'); await editor.post('/api/v1/admin/events', event({ title: 'Not yet', published: false })); const list = (await visitor.get('/api/v1/events')).body.events; assert.deepEqual(list.map((e: { title: string }) => e.title), ['Family camp']); assert.equal(list[0].startsAt, '2026-12-12T07:00:00.000Z'); assert.equal(list[0].endsAt, '2026-12-13T13:00:00.000Z'); assert.equal((await visitor.get(`/api/v1/events/${created.body.slug}`)).body.event.location, 'Magaliesberg'); assert.equal((await editor.post('/api/v1/admin/events', event({ endDate: '2026-12-11' }))).status, 400); }); it('publishes its own events as crosscode.event/1 and lists removals', async () => { const { h, editor, visitor } = await setup(); const { id } = (await editor.post('/api/v1/admin/events', event())).body; const feed = await visitor.get('/api/feed/v1/events'); assert.equal(feed.status, 200); const parsed = eventFeedSchema.parse(feed.body); assert.equal(parsed.events[0]!.schema, EVENT_SCHEMA); assert.deepEqual(parsed.events[0]!.origin, { product: 'app', installId: INSTALL_ID, url: 'https://app.hope.test/events/family-camp-2026-12-12' }); await editor.del(`/api/v1/admin/events/${id}`); assert.deepEqual((await visitor.get('/api/feed/v1/events')).body.deleted.map((d: { id: string }) => d.id), [id]); await h.ctx.settings.set('feed_publish', 'false'); assert.equal((await visitor.get('/api/feed/v1/events')).status, 404); }); it('shows Cross Events\' events from the feed with "Register on the Events site" and a canonical', async () => { const { h, visitor, editor } = await setup(); await h.db.productLink.create({ data: { installId: EVENTS_INSTALL, product: 'events', url: 'http://events.hope.test', publicKey: 'x', secret: h.ctx.secrets.encrypt('s'), connectedAt: new Date() } }); const theirs = { schema: EVENT_SCHEMA, id: '9e8d7c6b-5a49-4382-a716-151413121110', origin: { product: 'events', installId: EVENTS_INSTALL, url: 'http://events.hope.test/events/youth-conference' }, status: 'published', updatedAt: '2026-11-30T10:00:00.000Z', title: 'Youth conference', summary: 'Three days', description: null, imageUrl: null, timezone: 'Africa/Johannesburg', startsAt: '2026-12-20T07:00:00.000Z', endsAt: '2026-12-22T15:00:00.000Z', allDay: false, sessions: [], location: null, campus: null, series: null, tags: [], registration: { mode: 'origin', url: 'http://events.hope.test/events/youth-conference', status: 'open', opensAt: null, closesAt: null, priceFrom: null }, }; globalThis.fetch = (async () => new Response(JSON.stringify({ schema: EVENT_FEED_SCHEMA, generatedAt: '2026-12-01T06:00:00.000Z', events: [theirs], deleted: [] }), { status: 200 })) as typeof fetch; assert.deepEqual(await syncAll(h.ctx), { links: 1, failed: 0 }); const list = (await visitor.get('/api/v1/events')).body.events; assert.equal(list[0].title, 'Youth conference'); assert.deepEqual(list[0].registration, { label: 'Register on the Events site', url: 'http://events.hope.test/events/youth-conference' }); assert.equal(list[0].canonical, 'http://events.hope.test/events/youth-conference'); // An imported event is never published again by the App (no loops). assert.equal((await visitor.get('/api/feed/v1/events')).body.events.length, 0); // "Show events from" off: the copies go. await editor.put('/api/v1/admin/events/feed', { showEvents: { [EVENTS_INSTALL]: false } }); assert.deepEqual((await visitor.get('/api/v1/events')).body.events, []); }); }); describe('the sitemap', () => { it('lists public announcements, devotionals and the App\'s own events; never members-only ones', async () => { const { editor, writer, visitor } = await setup(); await editor.post('/api/v1/admin/announcements', announcement()); await editor.post('/api/v1/admin/announcements', announcement({ title: 'Members only', audience: 'members' })); await editor.post('/api/v1/admin/events', event()); await writer.put('/api/v1/admin/devotionals/settings', { source: 'church' }); await writer.post('/api/v1/admin/devotionals', { date: '2026-12-01', title: 'A', reference: 'John 3:16', translation: 'BSB', passageText: 'x', body: 'y' }); await writer.post('/api/v1/admin/devotionals', { date: '2026-11-30', title: 'B', reference: 'John 3:17', translation: 'BSB', passageText: 'x', body: 'y', membersOnly: true }); const map = (await visitor.get('/api/v1/sitemap')).body; assert.deepEqual(map.announcements.map((a: { slug: string }) => a.slug), ['family-camp-registrations-open']); assert.deepEqual(map.devotionals.map((d: { date: string }) => d.date), ['2026-12-01']); assert.deepEqual(map.events.map((e: { key: string }) => e.key), ['family-camp-2026-12-12']); assert.equal((await visitor.get('/api/v1/app')).body.url, 'https://app.hope.test'); }); });