// 3.7.0 (docs/WEBSITE-1.0-PLAN.md ยง9): the church profile from Accounts for the public pages (its // brand style and the shared footer), kept in memory and fetched again on church.changed. import fs from 'fs'; import path from 'path'; import express from 'express'; import request from 'supertest'; type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date }; const mockLinks: Link[] = []; jest.mock('../src/config/db', () => ({ productLink: { findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null, findUnique: async ({ where }: { where: { installId: string } }) => mockLinks.find((l) => l.installId === where.installId) ?? null, }, })); jest.mock('../src/jobs', () => ({ enqueueTask: async () => ({ queued: true }) })); process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption'; import { CHURCH_PATHS } from '@crosscode/contracts'; import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing'; import { churchProfile, resetChurchProfile } from '../src/accounts/church'; import { crossProductRouter } from '../src/links/routes'; import { getChurch } from '../src/v2/resources/church'; // eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS const { encrypt } = require('../src/utils/encryption') as { encrypt(v: string): string }; const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples'); const sample = (name: string) => JSON.parse(fs.readFileSync(path.join(SAMPLES, name), 'utf8')); const ACCOUNTS_ID = '5c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f'; const SECRET = 'link-secret-for-the-test-0123456789'; let profile = sample('church.json'); let answers: (number | 'down')[] = []; let fetches = 0; const realFetch = global.fetch; beforeAll(() => { global.fetch = (async (url: string) => { fetches++; expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`); const next = answers.shift() ?? 200; if (next === 'down') throw new Error('connect ECONNREFUSED'); return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } }); }) as typeof fetch; }); afterAll(() => { global.fetch = realFetch; }); beforeEach(() => { resetChurchProfile(); mockLinks.length = 0; answers = []; fetches = 0; profile = sample('church.json'); jest.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { jest.restoreAllMocks(); }); const connectAccounts = () => mockLinks.push({ installId: ACCOUNTS_ID, product: 'accounts', url: 'https://accounts.hope.test/', secret: encrypt(SECRET), updatedAt: new Date() }); function app() { const a = express(); a.use('/api', crossProductRouter()); return a; } function changed(body: object, { from = ACCOUNTS_ID, secret = SECRET } = {}) { const raw = JSON.stringify(body); const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret, rawBody: raw }); return request(app()).post(CHURCH_PATHS.changed).set({ 'content-type': 'application/json', ...headers }).send(raw); } describe('the church profile', () => { test('none without Accounts, and nothing is fetched', async () => { expect(await churchProfile()).toBeNull(); expect(fetches).toBe(0); }); test("fetched from the church's Accounts, with its brand style, and kept", async () => { connectAccounts(); const c = await churchProfile(); expect(c?.branding.style).toEqual({ fontPairing: 'warm', corners: 'soft' }); expect(c?.name).toBe(profile.name); await churchProfile(); expect(fetches).toBe(1); }); test('a pairing this version doesn\'t know reads as none, so the page keeps its fonts', async () => { connectAccounts(); profile.branding.style = { fontPairing: 'from-the-future', corners: 'round' }; expect((await churchProfile())?.branding.style).toEqual({ fontPairing: null, corners: 'round' }); }); test('Accounts down: none at first, then the last copy is kept while it is down', async () => { connectAccounts(); answers = ['down']; expect(await churchProfile()).toBeNull(); resetChurchProfile(); expect((await churchProfile())?.name).toBe(profile.name); }); test('a profile that isn\'t crosscode.church/1 isn\'t used', async () => { connectAccounts(); profile = { hello: 'world' }; expect(await churchProfile()).toBeNull(); }); test('GET /api/v2/church answers it, cacheable for a minute', async () => { connectAccounts(); const headers: Record = {}; const res = { setHeader: (k: string, v: string) => { headers[k] = v; } }; const out = await getChurch.handler({ res } as never); expect(getChurch.response.safeParse(out).success).toBe(true); expect((out as { data: { name: string } }).data.name).toBe(profile.name); expect(headers['Cache-Control']).toBe('public, max-age=60'); }); }); describe('church.changed from Accounts', () => { test('fetches the profile again (the last copy until then)', async () => { connectAccounts(); await churchProfile(); profile.branding.style = { fontPairing: 'classic', corners: 'sharp' }; expect((await churchProfile())?.branding.style?.fontPairing).toBe('warm'); const res = await changed(sample('church-changed.json')); expect(res.status).toBe(202); expect((await churchProfile())?.branding.style).toEqual({ fontPairing: 'classic', corners: 'sharp' }); expect(fetches).toBe(2); }); test('refuses a wrong signature, a sender that isn\'t Accounts and a body that isn\'t church.changed', async () => { connectAccounts(); mockLinks.push({ installId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', product: 'website', url: 'https://www.hope.test', secret: encrypt(SECRET), updatedAt: new Date() }); expect((await changed(sample('church-changed.json'), { secret: 'not-the-secret-at-all-0123456789' })).status).toBe(401); expect((await changed(sample('church-changed.json'), { from: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' })).status).toBe(404); const bad = await changed({ type: 'something.else' }); expect(bad.status).toBe(400); expect(bad.body.code).toBe('INVALID_REQUEST'); }); });