Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58960b5e93 | ||
|
|
79121bc447 | ||
|
|
36ceb358b8 | ||
|
|
a3a158faa8 | ||
|
|
ae604268e0 | ||
|
|
ae122a664a | ||
|
|
62d9728b95 | ||
|
|
ee129fbd87 | ||
|
|
10be55d261 | ||
|
|
ed97956a2f | ||
|
|
e79e5a11f9 | ||
|
|
66557c7f1d | ||
|
|
f4b6a41f83 |
@@ -2,6 +2,16 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## events@3.7.0 + @crosscode/ui 0.3.0 - 2026-11-24
|
||||
|
||||
Cross Events' public pages use the church's brand style and the shared footer (WEBSITE-1.0-PLAN §9).
|
||||
Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
- **Events 3.7.0:** the church profile from Accounts (`GET /api/v2/church`), its fonts and corners
|
||||
on the public pages, `ChurchFooter` and links to the church's other sites; `church.changed` is
|
||||
accepted at `/api/church/v1/changed`. Dashboard and setup unchanged. No migrations.
|
||||
- **`@crosscode/ui` 0.3.0:** `ChurchFooter` takes `bottom` (a product's own links).
|
||||
|
||||
## contracts@1.17.0 + accounts@1.7.0 + @crosscode/ui 0.2.0 - 2026-11-24
|
||||
|
||||
The first release of the Church Website 1.0.0 work (WEBSITE-1.0-PLAN §12). The contracts are
|
||||
|
||||
@@ -5,6 +5,38 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.7.0] - 2026-11-24
|
||||
|
||||
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). **Requires Accounts 1.7.0**
|
||||
(WHATS-NEW.md says so, and the Hub updates Accounts first) for the brand style. No migrations, no
|
||||
new settings.
|
||||
|
||||
### Added
|
||||
|
||||
- **The church's fonts and corners on the public pages.** The backend reads the church profile from
|
||||
Accounts (`GET /api/church/v1`, kept for 10 minutes; `src/accounts/church.ts`) and the public
|
||||
pages get it from the new `GET /api/v2/church` (public). `<html>` gets `brandAttributes(style)`
|
||||
from `@crosscode/ui` and the root layout imports `@crosscode/ui/fonts.css` (self-hosted, so no
|
||||
font is loaded from another site). Body text and h1–h3 use `--cc-font-body` and
|
||||
`--cc-font-heading` when the church picked a pairing, and `--radius` follows the corner style
|
||||
(`soft` is 0.5rem, the same as before). The dashboard and setup screens (`data-cc-staff`) keep
|
||||
the system fonts and 0.5rem.
|
||||
- **`church.changed` from Accounts** at `POST /api/church/v1/changed` (signed with the Accounts
|
||||
link, `LINK_HEADERS`): the profile is fetched again on the next page. Before 3.7.0 this answered
|
||||
404 and Accounts kept retrying for a week.
|
||||
- **The shared church footer** (`ChurchFooter`, `@crosscode/ui` 0.3.0) on the public pages when
|
||||
Accounts is connected: name and logo, service times, address, contact, social links and links
|
||||
to the church's other sites and the privacy notice, with Terms of Use and cookie settings below.
|
||||
Without Accounts, and on the dashboard (`<Footer plain />`), the footer is as before.
|
||||
- **Links to the church's other sites** in the header of the public pages (its Website, later its
|
||||
App), from the profile's `links`.
|
||||
|
||||
### Changed
|
||||
|
||||
- `@crosscode/ui` 0.3.0: `ChurchFooter` takes `bottom` (a product's own links after the copyright).
|
||||
- Frontend: `transpilePackages: ["@crosscode/ui"]`; Tailwind scans `packages/ui/src` and has
|
||||
`brand` (brand-700) for the shared footer.
|
||||
|
||||
## [3.6.1] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -12,6 +12,14 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.7.0 — requires accounts 1.7.0
|
||||
|
||||
- **Your public pages look like the rest of your church's sites.** With sign-in through your
|
||||
church's Accounts, the event pages use the fonts and corner style picked under Accounts → Admin →
|
||||
Brand style (as your sign-in pages, and later your church website, do), and a new footer shows your service times,
|
||||
address, contact details, social links and links to your other sites. The dashboard looks the same
|
||||
as before.
|
||||
|
||||
## 3.6.1
|
||||
|
||||
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand
|
||||
* style (fonts and corners) and what the shared footer shows (service times, address, contact,
|
||||
* social, the church's other sites). Accounts owns it and serves it publicly at
|
||||
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`).
|
||||
*
|
||||
* Fetched again after 10 minutes, or at once when Accounts sends `church.changed`
|
||||
* (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last
|
||||
* copy is kept and it's tried again after a minute; a site without Accounts has none, and its
|
||||
* pages look as they always have.
|
||||
*/
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import { accountsLink } from './client';
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
|
||||
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
let cached: Cached | null = null;
|
||||
let pending: Promise<Church | null> | null = null;
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
const parsed = churchSchema.safeParse(await res.json());
|
||||
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
/** The church's profile, or null when Accounts isn't connected or hasn't answered yet. Never throws. */
|
||||
export async function churchProfile(): Promise<Church | null> {
|
||||
let link;
|
||||
try {
|
||||
link = await accountsLink();
|
||||
} catch {
|
||||
return cached?.church ?? null;
|
||||
}
|
||||
if (!link) return null;
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!pending) {
|
||||
const last = cached?.url === url ? cached.church : null;
|
||||
pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
cached = { url, church, at: Date.now(), ok: true };
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
cached = { url, church: last, at: Date.now(), ok: false };
|
||||
return last;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */
|
||||
export function churchChanged(): void {
|
||||
if (cached) cached = { ...cached, at: 0 };
|
||||
}
|
||||
|
||||
/** Tests: start with nothing. */
|
||||
export function resetChurchProfile(): void {
|
||||
cached = null;
|
||||
pending = null;
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
*
|
||||
* GET /api/feed/v1/events?updatedSince= crosscode.event-feed/1 (public; "Publish my events")
|
||||
* POST /api/feed/v1/changed event.changed from a linked product (LINK_HEADERS)
|
||||
* POST /api/church/v1/changed church.changed from the church's Accounts (3.7.0)
|
||||
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
|
||||
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
|
||||
*
|
||||
@@ -11,11 +12,12 @@
|
||||
*/
|
||||
import express, { type Request, type Response, type Router } from 'express';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
|
||||
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
|
||||
import { hubInstallId, publishOn } from '../feed/context';
|
||||
import { feedResponse, lastRefresh, refreshOnce } from '../feed/entries';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect';
|
||||
import { churchChanged } from '../accounts/church';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
@@ -74,6 +76,25 @@ export function crossProductRouter(): Router {
|
||||
}
|
||||
});
|
||||
|
||||
// 3.7.0: the church profile changed in Accounts (its brand style, footer details): fetch it again.
|
||||
router.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), limiter(300), express.raw({ type: () => true, limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const sender = String(req.get(LINK_HEADERS.sender) || '');
|
||||
const link = sender ? await prisma.productLink.findUnique({ where: { installId: sender } }) : null;
|
||||
if (!link || link.product !== 'accounts') return fail(res, 404, 'NOT_LINKED', 'This site has no link with that Accounts.');
|
||||
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
|
||||
const check = verify({ secret: decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody });
|
||||
if (!check.ok) return fail(res, 401, check.code, "The signature doesn't match this link.");
|
||||
let body: unknown;
|
||||
try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; }
|
||||
if (!churchChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', "That isn't a church.changed message.");
|
||||
churchChanged();
|
||||
return res.status(202).json({ accepted: true });
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
router.post(LINK_PATHS.connect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
|
||||
try {
|
||||
return res.json(await acceptConnect(req.body, getClientIp(req)));
|
||||
|
||||
@@ -26,6 +26,7 @@ import './resources/ai';
|
||||
import './resources/feedback';
|
||||
import './resources/linkedProducts';
|
||||
import './resources/signIn';
|
||||
import './resources/church';
|
||||
|
||||
const pkg = require('../../package.json') as { version: string };
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { churchSchema } from '@crosscode/contracts';
|
||||
import { defineRoute } from '../route';
|
||||
import { single } from '../paging';
|
||||
import { churchProfile } from '../../accounts/church';
|
||||
|
||||
/**
|
||||
* The church profile for the public pages (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): its brand style
|
||||
* (fonts, corners) and the shared footer's details, from the church's Accounts
|
||||
* (src/accounts/church.ts). null when Accounts isn't connected.
|
||||
*/
|
||||
export const getChurch = defineRoute({
|
||||
method: 'get',
|
||||
path: '/church',
|
||||
tag: 'Site',
|
||||
summary: "The church's profile",
|
||||
description: "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.",
|
||||
access: 'public',
|
||||
response: single(churchSchema.nullable()),
|
||||
async handler({ res }) {
|
||||
res.setHeader('Cache-Control', 'public, max-age=60');
|
||||
return { data: await churchProfile() };
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
// 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<string, string> = {};
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import path from "path";
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { test, expect, loginAs, seed } from "./fixtures";
|
||||
|
||||
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9 and §13): with the church's Accounts connected, the public
|
||||
// pages use the church's fonts and corners from its profile and the shared church footer, as the
|
||||
// Website and Accounts' own pages do. The dashboard stays as it is. Accounts runs in memory
|
||||
// (e2e/support/accounts-server.mts); afterwards the link is removed, so the other specs see the
|
||||
// site as before.
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
|
||||
const backend = path.join(__dirname, "..", "backend");
|
||||
require(require.resolve("dotenv", { paths: [backend] })).config({ path: path.join(backend, ".env") });
|
||||
const { Client } = require(require.resolve("pg", { paths: [backend] }));
|
||||
const { e2eDatabaseUrl } = require("./support/db-url");
|
||||
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
|
||||
const { encrypt } = require(path.join(backend, "src", "utils", "encryption"));
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const ACCOUNTS_API = "http://127.0.0.1:5221";
|
||||
const ACCOUNTS_ID = "7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b";
|
||||
const TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
|
||||
|
||||
async function sql(text: string, values: unknown[] = []) {
|
||||
const client = new Client({ connectionString: e2eDatabaseUrl() });
|
||||
await client.connect();
|
||||
try {
|
||||
return (await client.query(text, values)).rows;
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
}
|
||||
|
||||
test.describe.serial("the church's brand style and footer", () => {
|
||||
test.beforeAll(async () => {
|
||||
const profile = await fetch(`${ACCOUNTS_API}/test/profile`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: "E2E Church",
|
||||
branding: { style: { fontPairing: "warm", corners: "round" } },
|
||||
serviceTimes: [{ day: "sunday", time: "09:00", label: "Morning service", campus: null, note: null }],
|
||||
contact: { email: "office@e2e.test", phone: "+27161234567", whatsapp: null, address: { line1: "1 Church Street", line2: null, suburb: null, city: "Vereeniging", postalCode: "1939" } },
|
||||
}),
|
||||
});
|
||||
expect(profile.ok, await profile.text()).toBe(true);
|
||||
// Linked to Accounts, as Connect would (the backend reads the profile from this address).
|
||||
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
|
||||
await sql(
|
||||
`INSERT INTO "ProductLink" ("installId", product, url, "publicKey", secret, "connectedAt", "createdAt", "updatedAt") VALUES ($1, 'accounts', $2, 'x', $3, now(), now(), now())`,
|
||||
[ACCOUNTS_ID, ACCOUNTS_API, encrypt(signing.newLinkSecret())],
|
||||
);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
|
||||
});
|
||||
|
||||
test("public pages: the church's fonts, round corners and the shared footer, all from this site", async ({ page }) => {
|
||||
const elsewhere: string[] = [];
|
||||
page.on("request", (r) => {
|
||||
if (r.resourceType() === "font" && !r.url().startsWith("http://localhost:3100/")) elsewhere.push(r.url());
|
||||
});
|
||||
// The site keeps the profile for a minute; reload until it's there.
|
||||
await expect(async () => {
|
||||
await page.goto("/events");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm", { timeout: 1000 });
|
||||
}).toPass({ timeout: 90_000 });
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
|
||||
await expect(page.getByText("E2E Free Evening")).toBeVisible();
|
||||
|
||||
const fonts = await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
const h1 = document.querySelector("h1");
|
||||
return {
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
heading: h1 ? getComputedStyle(h1).fontFamily : "",
|
||||
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
|
||||
loaded: [...document.fonts].filter((f) => f.status === "loaded").map((f) => f.family.replace(/"/g, "")),
|
||||
};
|
||||
});
|
||||
expect(fonts.body).toContain("CC Nunito Sans");
|
||||
expect(fonts.heading).toContain("CC Fraunces");
|
||||
expect(fonts.radius).toBe("0.75rem");
|
||||
expect(fonts.loaded).toContain("CC Nunito Sans");
|
||||
|
||||
const footer = page.locator("footer");
|
||||
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
|
||||
await expect(footer).toContainText("Sundays 09:00");
|
||||
await expect(footer).toContainText("1 Church Street");
|
||||
await expect(footer.getByRole("link", { name: "+27161234567" })).toHaveAttribute("href", "tel:+27161234567");
|
||||
await expect(footer.getByRole("link", { name: "Your account" })).toHaveAttribute("href", /127\.0\.0\.1/);
|
||||
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/legal/privacy");
|
||||
await expect(footer.getByRole("link", { name: "Terms of Use" })).toBeVisible();
|
||||
await expect(footer.getByRole("button", { name: /cookie/i })).toBeVisible();
|
||||
|
||||
await page.goto(`/events/${seed().events.course}`);
|
||||
await expect(page.getByRole("heading", { name: "E2E Alpha Course" })).toBeVisible();
|
||||
await expect(page.locator("footer").getByRole("heading", { name: "Service times" })).toBeVisible();
|
||||
await page.waitForLoadState("networkidle");
|
||||
const results = await new AxeBuilder({ page }).withTags(TAGS).analyze();
|
||||
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
|
||||
expect(elsewhere).toEqual([]);
|
||||
});
|
||||
|
||||
test("the dashboard keeps its own fonts, corners and footer", async ({ page }) => {
|
||||
await loginAs(page, "admin");
|
||||
await page.goto("/dashboard");
|
||||
await expect(page.locator("[data-cc-staff]").first()).toBeVisible();
|
||||
await expect(page.locator("main")).toBeVisible();
|
||||
const look = await page.evaluate(() => ({
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
|
||||
}));
|
||||
expect(look.body).not.toContain("CC ");
|
||||
expect(look.radius).toBe("0.5rem");
|
||||
await expect(page.locator("footer")).toContainText("All rights reserved");
|
||||
});
|
||||
});
|
||||
@@ -5,11 +5,13 @@
|
||||
* differs from the Events site's (localhost), so their cookies stay apart as on two domains.
|
||||
*
|
||||
* Test helpers: POST /test/link { installId, url, secret } links Events, as Connect would;
|
||||
* GET /test/code?to=<email> answers the last code emailed to that address.
|
||||
* GET /test/code?to=<email> answers the last code emailed to that address; POST /test/profile changes
|
||||
* the church profile (3.7.0, church-brand.spec.ts), as an admin's save in Accounts would.
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import { createApp } from '../../../accounts/backend/src/app.ts';
|
||||
import { updateProfile } from '../../../accounts/backend/src/church/profile.ts';
|
||||
import { createCtx } from '../../../accounts/backend/src/context.ts';
|
||||
import { loadConfig } from '../../../accounts/backend/src/lib/config.ts';
|
||||
import { MemoryMessenger } from '../../../accounts/backend/src/lib/messages.ts';
|
||||
@@ -33,6 +35,19 @@ http.createServer((req, res) => {
|
||||
res.writeHead(200, { 'content-type': 'text/plain' }).end(messenger.lastCode(to) ?? '');
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/test/profile') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
req.on('end', async () => {
|
||||
try {
|
||||
const church = await updateProfile(ctx, JSON.parse(body));
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(church));
|
||||
} catch (e) {
|
||||
res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ message: (e as Error).message }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/test/link') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
|
||||
@@ -14,6 +14,8 @@ const nextConfig: NextConfig = {
|
||||
// The end-to-end tests run their own dev server; a separate build folder keeps it
|
||||
// from clashing with one already running.
|
||||
distDir: process.env.NEXT_DIST_DIR || ".next",
|
||||
// The shared fonts and footer (3.7.0) are TypeScript source.
|
||||
transpilePackages: ["@crosscode/ui"],
|
||||
images: {
|
||||
// (images.domains is deprecated in Next 16.)
|
||||
remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -12,6 +12,7 @@
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@hookform/resolvers": "^5.2.1",
|
||||
"@radix-ui/react-accordion": "^1.2.11",
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
// Don't render protected content until auth state is known
|
||||
if (loading || !user) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div data-cc-staff className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-sm text-gray-400">Loading…</div>
|
||||
</div>
|
||||
);
|
||||
@@ -88,7 +88,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
// scroll) so the sidebar can be a plain sibling column that never
|
||||
// scrolls — only the content column (main + footer) scrolls internally.
|
||||
return (
|
||||
<div className="h-screen flex flex-col overflow-hidden">
|
||||
<div data-cc-staff className="h-screen flex flex-col overflow-hidden">
|
||||
<Navbar />
|
||||
<LicenceBanner />
|
||||
<ProviderNotices />
|
||||
@@ -99,7 +99,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
<Sidebar />
|
||||
<div className="flex-1 min-w-0 flex flex-col overflow-y-auto">
|
||||
<main className="flex-1 p-6 bg-gray-50">{children}</main>
|
||||
<Footer />
|
||||
<Footer plain />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -107,14 +107,14 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<div data-cc-staff className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
<LicenceBanner />
|
||||
<ProviderNotices />
|
||||
<PrivacyPrompts />
|
||||
<CommandPalette />
|
||||
<main className="flex-1 p-6 bg-gray-50">{children}</main>
|
||||
<Footer />
|
||||
<Footer plain />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 243 75% 59%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
/* The church's corners (3.7.0, @crosscode/ui fonts.css): soft (0.5rem) unless it picked others. */
|
||||
--radius: var(--cc-radius-sm, 0.5rem);
|
||||
|
||||
/* Fallback brand scale (matches the pre-branding-feature default indigo, brand-600 #4F46E5) */
|
||||
--brand-50: #EEF2FF;
|
||||
@@ -73,6 +74,30 @@ html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
/*
|
||||
* The church's fonts (3.7.0, docs/WEBSITE-1.0-PLAN.md §3 and §9): <html> gets
|
||||
* data-cc-fonts from its brand style in Accounts, and @crosscode/ui/fonts.css sets these
|
||||
* variables. Without a pairing they're unset and the page keeps Tailwind's system fonts.
|
||||
* The dashboard and setup screens (data-cc-staff) stay as they are.
|
||||
*/
|
||||
@layer base {
|
||||
body {
|
||||
font-family: var(--cc-font-body, theme("fontFamily.sans"));
|
||||
}
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
html:has([data-cc-staff]) {
|
||||
--cc-font-body: initial;
|
||||
--cc-font-heading: initial;
|
||||
--cc-heading-variation: initial;
|
||||
--cc-radius-sm: initial;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Accessibility (WCAG 2.2 AA, 1.50.0): a clear focus ring for keyboard users on every
|
||||
* focusable element (mouse clicks don't show it), in the brand colour with a white halo
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { AuthProvider } from "@/contexts/AuthContext";
|
||||
import { SiteSettingsProvider } from "@/contexts/SiteSettingsContext";
|
||||
import { ToastProvider } from "@/components/shared/ToastProvider";
|
||||
@@ -11,6 +13,8 @@ import { ImpersonationBanner } from "@/components/shared/ImpersonationBanner";
|
||||
import { SkipLink } from "@/components/layout/SkipLink";
|
||||
import { resolveToApiOrigin } from "@/lib/api";
|
||||
import { getServerSettings } from "@/lib/serverSettings";
|
||||
import { getServerChurch } from "@/lib/serverChurch";
|
||||
import { ChurchProvider } from "@/contexts/ChurchContext";
|
||||
import { buildThemeCssVars } from "@/lib/colorScale";
|
||||
import { appUrl } from "@/lib/siteConfig";
|
||||
|
||||
@@ -49,7 +53,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
}
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const settings = await getServerSettings();
|
||||
const [settings, church] = await Promise.all([getServerSettings(), getServerChurch()]);
|
||||
const cssVars = buildThemeCssVars({
|
||||
primary: settings.primary_color || settings.accent_color,
|
||||
secondary: settings.secondary_color,
|
||||
@@ -57,12 +61,15 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
});
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
// The church's fonts and corners from Accounts (3.7.0): used by the public pages; the
|
||||
// dashboard and setup screens keep their own (globals.css, data-cc-staff).
|
||||
<html lang="en" {...brandAttributes(church?.branding.style)}>
|
||||
<body>
|
||||
{cssVars && (
|
||||
<style id="brand-theme" dangerouslySetInnerHTML={{ __html: `:root{${cssVars}}` }} />
|
||||
)}
|
||||
<SkipLink />
|
||||
<ChurchProvider church={church}>
|
||||
<SiteSettingsProvider initialSettings={settings}>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
@@ -75,6 +82,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</SiteSettingsProvider>
|
||||
</ChurchProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ export default function SetupPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
|
||||
<div data-cc-staff className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
|
||||
<div className={`bg-white rounded-2xl shadow-lg w-full p-8 transition-all ${step === 3 ? "max-w-4xl" : "max-w-lg"}`}>
|
||||
|
||||
{/* Heading */}
|
||||
|
||||
@@ -1,30 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { ChurchFooter } from "@crosscode/ui";
|
||||
import { appName } from "@/lib/siteConfig";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { useChurch } from "@/contexts/ChurchContext";
|
||||
import { CookieSettingsButton } from "@/components/shared/CookieSettingsButton";
|
||||
|
||||
export const Footer = () => {
|
||||
/**
|
||||
* The public pages' footer. With the church's Accounts connected (3.7.0) it's the shared church
|
||||
* footer (as on the Website and Accounts' pages): name and logo, service times, address, contact,
|
||||
* social links and the church's other sites, with this site's terms and cookie settings below.
|
||||
* `plain`: the dashboard's own footer, as before.
|
||||
*/
|
||||
export const Footer = ({ plain = false }: { plain?: boolean }) => {
|
||||
const { settings } = useSiteSettings();
|
||||
const church = useChurch();
|
||||
const displayName = settings.org_name || appName;
|
||||
|
||||
return (
|
||||
<>
|
||||
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
|
||||
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
|
||||
<div className="mt-2 space-x-4">
|
||||
<Link href="/legal/terms" className="hover:underline text-gray-300">
|
||||
Terms of Use
|
||||
</Link>
|
||||
<Link href="/legal/privacy" className="hover:underline text-gray-300">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
<CookieSettingsButton className="hover:underline text-gray-300" />
|
||||
</div>
|
||||
</footer>
|
||||
{church && !plain ? (
|
||||
<ChurchFooter
|
||||
church={church}
|
||||
current="events"
|
||||
privacyUrl="/legal/privacy"
|
||||
bottom={
|
||||
<>
|
||||
<Link href="/legal/terms" className="hover:underline">Terms of Use</Link>
|
||||
<CookieSettingsButton className="hover:underline" />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
|
||||
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
|
||||
<div className="mt-2 space-x-4">
|
||||
<Link href="/legal/terms" className="hover:underline text-gray-300">
|
||||
Terms of Use
|
||||
</Link>
|
||||
<Link href="/legal/privacy" className="hover:underline text-gray-300">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
<CookieSettingsButton className="hover:underline text-gray-300" />
|
||||
</div>
|
||||
</footer>
|
||||
)}
|
||||
{/* Spacer so content isn't hidden behind the fixed mobile bottom nav */}
|
||||
<div className="h-16 md:hidden" aria-hidden="true" />
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -9,6 +9,8 @@ import { BottomNav } from "./BottomNav";
|
||||
import defaultLogo from "@/app/default_logo.png";
|
||||
import { appName } from "@/lib/siteConfig";
|
||||
import { resolveToApiOrigin } from "@/lib/api";
|
||||
import { productLinks } from "@crosscode/ui";
|
||||
import { useChurch } from "@/contexts/ChurchContext";
|
||||
|
||||
type NavLink = {
|
||||
href: string;
|
||||
@@ -20,6 +22,10 @@ export const Navbar = () => {
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
const { settings, loading: settingsLoading } = useSiteSettings();
|
||||
const pathname = usePathname();
|
||||
const church = useChurch();
|
||||
// The church's other sites from its profile in Accounts (3.7.0): its Website, later its App.
|
||||
// Not on the dashboard, which stays as it is.
|
||||
const otherSites = church && !pathname?.startsWith("/dashboard") ? productLinks(church.links, "events") : [];
|
||||
const displayName = settings.org_name || appName;
|
||||
const logoSrc = settings.logo_url ? resolveToApiOrigin(settings.logo_url) : null;
|
||||
|
||||
@@ -94,6 +100,11 @@ export const Navbar = () => {
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
{otherSites.map(site => (
|
||||
<a key={site.href} href={site.href} className="text-sm pb-0.5 border-b-2 border-transparent text-gray-700 transition-colors hover:text-brand-600">
|
||||
{site.label}
|
||||
</a>
|
||||
))}
|
||||
|
||||
{/* Auth links are only known once the token has been validated —
|
||||
rendering nothing here (instead of guessing "logged out") avoids
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext } from "react";
|
||||
import type { Church } from "@crosscode/contracts";
|
||||
|
||||
/** The church profile from Accounts (3.7.0), fetched once by the root layout; null without Accounts. */
|
||||
const ChurchContext = createContext<Church | null>(null);
|
||||
|
||||
export function ChurchProvider({ church, children }: { church: Church | null; children: React.ReactNode }) {
|
||||
return <ChurchContext.Provider value={church}>{children}</ChurchContext.Provider>;
|
||||
}
|
||||
|
||||
export const useChurch = () => useContext(ChurchContext);
|
||||
@@ -74271,6 +74271,648 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/church": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Site"
|
||||
],
|
||||
"summary": "The church's profile",
|
||||
"description": "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.\n\n**Who:** Anyone.",
|
||||
"operationId": "getChurch",
|
||||
"parameters": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.church/1"
|
||||
},
|
||||
"customerId": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"shortName": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 30
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"timezone": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
|
||||
},
|
||||
"locale": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"
|
||||
},
|
||||
"branding": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"logoUrl": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"iconUrl": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"colours": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"primary": {
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
"accent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"primary",
|
||||
"accent"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"style": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fontPairing": {
|
||||
"default": null,
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"classic",
|
||||
"scholarly",
|
||||
"editorial",
|
||||
"impact",
|
||||
"contemporary",
|
||||
"friendly",
|
||||
"warm",
|
||||
"modern"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"corners": {
|
||||
"default": null,
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"sharp",
|
||||
"soft",
|
||||
"round"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"fontPairing",
|
||||
"corners"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"logoUrl",
|
||||
"iconUrl",
|
||||
"colours"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"campuses": {
|
||||
"maxItems": 50,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"slug": {
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"address": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"line1": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"line2": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"suburb": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"city": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
},
|
||||
"province": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"postalCode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 20
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"country": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z]{2}$"
|
||||
},
|
||||
"geo": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lat": {
|
||||
"type": "number",
|
||||
"minimum": -90,
|
||||
"maximum": 90
|
||||
},
|
||||
"lng": {
|
||||
"type": "number",
|
||||
"minimum": -180,
|
||||
"maximum": 180
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"lat",
|
||||
"lng"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"line1",
|
||||
"line2",
|
||||
"suburb",
|
||||
"city",
|
||||
"province",
|
||||
"postalCode",
|
||||
"country",
|
||||
"geo"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"slug",
|
||||
"name",
|
||||
"address"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"serviceTimes": {
|
||||
"maxItems": 100,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"day": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
"sunday"
|
||||
]
|
||||
},
|
||||
"time": {
|
||||
"type": "string",
|
||||
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"
|
||||
},
|
||||
"label": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"campus": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"note": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"day",
|
||||
"time",
|
||||
"label",
|
||||
"campus",
|
||||
"note"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"contact": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 254,
|
||||
"format": "email",
|
||||
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"phone": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"address": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"line1": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"line2": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"suburb": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"city": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
},
|
||||
"province": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"postalCode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 20
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"country": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z]{2}$"
|
||||
},
|
||||
"geo": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lat": {
|
||||
"type": "number",
|
||||
"minimum": -90,
|
||||
"maximum": 90
|
||||
},
|
||||
"lng": {
|
||||
"type": "number",
|
||||
"minimum": -180,
|
||||
"maximum": 180
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"lat",
|
||||
"lng"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"line1",
|
||||
"line2",
|
||||
"suburb",
|
||||
"city",
|
||||
"province",
|
||||
"postalCode",
|
||||
"country",
|
||||
"geo"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"phone",
|
||||
"whatsapp",
|
||||
"address"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"social": {
|
||||
"maxItems": 20,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"network": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"facebook",
|
||||
"instagram",
|
||||
"youtube",
|
||||
"tiktok",
|
||||
"x",
|
||||
"spotify",
|
||||
"whatsapp-channel",
|
||||
"other"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"network",
|
||||
"url"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"links": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"website": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"events": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"app": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"accounts": {
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"website",
|
||||
"events",
|
||||
"app",
|
||||
"accounts"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"customerId",
|
||||
"updatedAt",
|
||||
"name",
|
||||
"shortName",
|
||||
"timezone",
|
||||
"locale",
|
||||
"branding",
|
||||
"campuses",
|
||||
"serviceTimes",
|
||||
"contact",
|
||||
"social",
|
||||
"links"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
|
||||
+125
@@ -7760,6 +7760,28 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/church": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The church's profile
|
||||
* @description The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.
|
||||
*
|
||||
* **Who:** Anyone.
|
||||
*/
|
||||
get: operations["getChurch"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
@@ -40739,4 +40761,107 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
getChurch: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
/** @constant */
|
||||
schema: "crosscode.church/1";
|
||||
/** Format: uuid */
|
||||
customerId: string;
|
||||
/** Format: date-time */
|
||||
updatedAt: string;
|
||||
name: string;
|
||||
shortName: string | null;
|
||||
timezone: string;
|
||||
locale: string;
|
||||
branding: {
|
||||
logoUrl: string | null;
|
||||
iconUrl: string | null;
|
||||
colours: {
|
||||
primary: string;
|
||||
accent: string | null;
|
||||
};
|
||||
style?: {
|
||||
/** @default null */
|
||||
fontPairing: ("classic" | "scholarly" | "editorial" | "impact" | "contemporary" | "friendly" | "warm" | "modern") | null;
|
||||
/** @default null */
|
||||
corners: ("sharp" | "soft" | "round") | null;
|
||||
};
|
||||
};
|
||||
campuses: {
|
||||
slug: string;
|
||||
name: string;
|
||||
address: {
|
||||
line1: string;
|
||||
line2: string | null;
|
||||
suburb: string | null;
|
||||
city: string;
|
||||
province: string | null;
|
||||
postalCode: string | null;
|
||||
country: string;
|
||||
geo: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
} | null;
|
||||
} | null;
|
||||
}[];
|
||||
serviceTimes: {
|
||||
/** @enum {string} */
|
||||
day: "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
|
||||
time: string;
|
||||
label: string | null;
|
||||
campus: string | null;
|
||||
note: string | null;
|
||||
}[];
|
||||
contact: {
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
whatsapp: string | null;
|
||||
address: {
|
||||
line1: string;
|
||||
line2: string | null;
|
||||
suburb: string | null;
|
||||
city: string;
|
||||
province: string | null;
|
||||
postalCode: string | null;
|
||||
country: string;
|
||||
geo: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
} | null;
|
||||
} | null;
|
||||
};
|
||||
social: {
|
||||
/** @enum {string} */
|
||||
network: "facebook" | "instagram" | "youtube" | "tiktok" | "x" | "spotify" | "whatsapp-channel" | "other";
|
||||
/** Format: uri */
|
||||
url: string;
|
||||
}[];
|
||||
links: {
|
||||
website: string | null;
|
||||
events: string | null;
|
||||
app: string | null;
|
||||
/** Format: uri */
|
||||
accounts: string;
|
||||
};
|
||||
} | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Church } from "@crosscode/contracts";
|
||||
import { API_BASE } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* The church profile from the church's Accounts (3.7.0), through the backend's
|
||||
* `GET /api/v2/church`: the brand style for `<html>` and the shared footer. null when Accounts
|
||||
* isn't connected or the backend can't be reached, and the pages look as they always have.
|
||||
* Fetched the same way as getServerSettings, so Next dedupes it within a request.
|
||||
*/
|
||||
export async function getServerChurch(): Promise<Church | null> {
|
||||
if (!API_BASE) return null;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/v2/church`, { next: { revalidate: 60 } });
|
||||
if (!res.ok) return null;
|
||||
return ((await res.json())?.data as Church | null) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
module.exports = {
|
||||
content: [
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
// The shared footer (3.7.0)
|
||||
"../../../packages/ui/src/**/*.{ts,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
@@ -47,6 +49,8 @@ module.exports = {
|
||||
// colorScale.ts's buildBrandScale + globals.css for the static
|
||||
// fallback defaults used when no setting is saved yet).
|
||||
brand: {
|
||||
// `brand` alone (the shared footer's links, @crosscode/ui)
|
||||
DEFAULT: "var(--brand-700)",
|
||||
50: "var(--brand-50)",
|
||||
100: "var(--brand-100)",
|
||||
200: "var(--brand-200)",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -0,0 +1,26 @@
|
||||
# Changelog — Church Website
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- The app's skeleton (WEBSITE-1.0-PLAN §1): an Express + Prisma backend with `/api/health` and
|
||||
`/api/v1/site/status` (Coming soon until the first publish), the content model and its first
|
||||
migration, the section variants per template (§3, decision 16) with the template switch rules, and
|
||||
a Next.js frontend with the Coming soon page, an admin placeholder and `robots.txt`.
|
||||
- **Signing in to the admin through the church's Accounts** (§10), as Cross Events 3.x: the Hub
|
||||
client (protocol v2, product `website`, registers from `HUB_LICENCE_KEY`, heartbeats with
|
||||
aggregate counts), links (`crosscode.link/1`; the Website connects itself to the church's Accounts
|
||||
once the Hub lists it), `/api/auth/signin`, `/callback`, `/me`, `/signout` (then Accounts'
|
||||
sign-out), back-channel logout and Accounts' calls (`user.updated`, `user.export`,
|
||||
`user.deleted`). The Website keeps its own session (`ccw_session`, only a hash stored) and its own
|
||||
roles; the **first Owner** is whoever signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`,
|
||||
verified in Accounts) while the site has none. Owners and Admins sign in with a second step
|
||||
(`two_factor_required_for_admins`, on by default); asked of Accounts once, then explained.
|
||||
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
|
||||
- **The church's export** (`scripts/export-church.ts`): `export.json` in
|
||||
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
|
||||
- **`crosscode`:** `scripts/products/website.sh` (the same hooks as Accounts, ports 5300 / 3300,
|
||||
uploads in the export), `crosscode add <church> website` (needs the church's Accounts; served on
|
||||
`www.<address>`, or the Cross Code address itself), and the installer shared by Accounts and the
|
||||
Website (`install_app`).
|
||||
+25
-1
@@ -1,3 +1,27 @@
|
||||
# Church Website
|
||||
|
||||
Placeholder: the church's public website and its admin. Built in phase 5 of ROADMAP-v3 (see §6 there).
|
||||
The church's public website and its admin (ROADMAP-v3 §6, phase 5; plan and decisions in
|
||||
[docs/WEBSITE-1.0-PLAN.md](../../docs/WEBSITE-1.0-PLAN.md)). Served at `www.<church's address>` (or
|
||||
`<church>.crosscode.co.za`), with the admin at `/admin`, signed in through the church's Accounts.
|
||||
The church picks one of four templates (Heritage, Bold, Community, Clean) and makes it its own with
|
||||
section variants and style settings. Changes are drafts until an editor previews the whole site and
|
||||
presses Publish; until the first publish visitors see Coming soon.
|
||||
|
||||
**State:** being built (2026-11-25): the skeleton and signing in through Accounts. Not released;
|
||||
`website@1.0.0` is tagged when the plan is built.
|
||||
|
||||
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
|
||||
client id at Accounts), links itself to the church's Accounts once the Hub lists it, and signs
|
||||
admins in through `@crosscode/auth-client`. Roles are the Website's own; the first Owner is whoever
|
||||
signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`), verified in Accounts. Locally, set
|
||||
`LINKS_ALLOW_PRIVATE=true` to link to an Accounts on http://localhost.
|
||||
|
||||
- `backend/`: Express + Prisma (ES modules), as Accounts. `npm run dev`, `npm test` (Node's test
|
||||
runner through tsx), `npm run build`. The content model is in `prisma/schema.prisma`; the section
|
||||
variants per template (plan §3, decision 16) in `src/site/variants.ts`.
|
||||
- `frontend/`: Next.js 16. The public site (server-rendered from the latest published version) and
|
||||
the admin.
|
||||
|
||||
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `WEBSITE_URL=http://localhost:3300`),
|
||||
`npx prisma migrate deploy`, then `npm run dev` in both folders (the frontend runs on 3300 and sends
|
||||
/api to the backend on 5300).
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# What's new in the Church Website
|
||||
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
src/generated/
|
||||
.env
|
||||
uploads/
|
||||
exports/
|
||||
/backups/
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"prisma": "^7.10.1",
|
||||
"supertest": "^7.3.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
|
||||
import 'dotenv/config';
|
||||
import { defineConfig } from 'prisma/config';
|
||||
|
||||
export default defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: { path: 'prisma/migrations' },
|
||||
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
|
||||
datasource: { url: process.env.DATABASE_URL ?? '' },
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §10).
|
||||
|
||||
-- CreateSchema
|
||||
CREATE SCHEMA IF NOT EXISTS "public";
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WebsiteRole" AS ENUM ('owner', 'admin', 'editor', 'ministry_leader', 'viewer');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PageKind" AS ENUM ('home', 'visit', 'about', 'leadership', 'ministries', 'events', 'messages', 'give', 'contact', 'terms', 'safeguarding', 'custom');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MessageSource" AS ENUM ('youtube_feed', 'youtube', 'spotify');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SiteDesign" (
|
||||
"id" INTEGER NOT NULL DEFAULT 1,
|
||||
"template" TEXT NOT NULL,
|
||||
"variants" JSONB NOT NULL,
|
||||
"home" JSONB NOT NULL,
|
||||
"style" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "SiteDesign_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Page" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kind" "PageKind" NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"seoTitle" TEXT,
|
||||
"description" TEXT,
|
||||
"navLabel" TEXT,
|
||||
"inNav" BOOLEAN NOT NULL DEFAULT true,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"imageId" TEXT,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Page_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Section" (
|
||||
"id" TEXT NOT NULL,
|
||||
"pageId" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"variant" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"data" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Ministry" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"summary" TEXT,
|
||||
"body" TEXT,
|
||||
"imageId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Leader" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT,
|
||||
"bio" TEXT,
|
||||
"photoId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Leader_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MessageSeries" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"summary" TEXT,
|
||||
"imageId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MessageSeries_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Message" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"date" TIMESTAMP(3) NOT NULL,
|
||||
"source" "MessageSource" NOT NULL,
|
||||
"mediaUrl" TEXT NOT NULL,
|
||||
"externalId" TEXT,
|
||||
"thumbnailUrl" TEXT,
|
||||
"speaker" TEXT,
|
||||
"passage" TEXT,
|
||||
"notes" TEXT,
|
||||
"seriesId" TEXT,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SimpleEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"endsAt" TIMESTAMP(3),
|
||||
"allDay" BOOLEAN NOT NULL DEFAULT false,
|
||||
"timezone" TEXT NOT NULL DEFAULT 'Africa/Johannesburg',
|
||||
"location" TEXT,
|
||||
"description" TEXT,
|
||||
"imageId" TEXT,
|
||||
"link" TEXT,
|
||||
"cancelled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "SimpleEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ImportedEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"originProduct" TEXT NOT NULL,
|
||||
"originId" TEXT NOT NULL,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"data" JSONB NOT NULL,
|
||||
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MediaAsset" (
|
||||
"id" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
"mime" TEXT NOT NULL,
|
||||
"bytes" INTEGER NOT NULL,
|
||||
"width" INTEGER,
|
||||
"height" INTEGER,
|
||||
"alt" TEXT NOT NULL DEFAULT '',
|
||||
"sizes" JSONB,
|
||||
"uploadedBy" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SiteVersion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"number" INTEGER NOT NULL,
|
||||
"snapshot" JSONB NOT NULL,
|
||||
"note" TEXT,
|
||||
"publishedBy" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PreviewLink" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "PreviewLink_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "WebsiteUser" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" "WebsiteRole" NOT NULL,
|
||||
"ministryId" TEXT,
|
||||
"lastSignInAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "WebsiteUser_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"sid" TEXT,
|
||||
"mfa" BOOLEAN NOT NULL DEFAULT false,
|
||||
"idToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProductLink" (
|
||||
"installId" TEXT NOT NULL,
|
||||
"product" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"publicKey" TEXT NOT NULL,
|
||||
"secret" TEXT NOT NULL,
|
||||
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"connectedById" TEXT,
|
||||
"lastSyncError" TEXT,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "LinkNonce" (
|
||||
"nonce" TEXT NOT NULL,
|
||||
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorRole" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"targetType" TEXT NOT NULL,
|
||||
"targetId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AppSetting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Page_slug_key" ON "Page"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Page_kind_idx" ON "Page"("kind");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Section_pageId_position_idx" ON "Section"("pageId", "position");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MessageSeries_slug_key" ON "MessageSeries"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Message_slug_key" ON "Message"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Message_externalId_key" ON "Message"("externalId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Message_date_idx" ON "Message"("date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SimpleEvent_slug_key" ON "SimpleEvent"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SiteVersion_number_key" ON "SiteVersion"("number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PreviewLink_tokenHash_key" ON "PreviewLink"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_tokenHash_key" ON "Session"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_sid_idx" ON "Session"("sid");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Message" ADD CONSTRAINT "Message_seriesId_fkey" FOREIGN KEY ("seriesId") REFERENCES "MessageSeries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WebsiteUser" ADD CONSTRAINT "WebsiteUser_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,301 @@
|
||||
// Church Website 1.0.0 (docs/WEBSITE-1.0-PLAN.md). One database per church.
|
||||
//
|
||||
// The content tables are the **working copy** the admin edits (§4). Publishing writes an immutable
|
||||
// snapshot of them to SiteVersion; visitors always see the latest SiteVersion, the preview sees the
|
||||
// working copy. Shared facts (name, logo, colours, service times, contact, the brand style) are the
|
||||
// church profile's, in Accounts (§2), and are never stored here.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
|
||||
output = "../src/generated/prisma"
|
||||
moduleFormat = "esm"
|
||||
importFileExtension = "js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
/// Website roles (§10). Held here, per product: an Events role gives nothing in the Website.
|
||||
enum WebsiteRole {
|
||||
owner
|
||||
admin
|
||||
editor
|
||||
ministry_leader
|
||||
viewer
|
||||
}
|
||||
|
||||
enum PageKind {
|
||||
home
|
||||
visit
|
||||
about
|
||||
leadership
|
||||
ministries
|
||||
events
|
||||
messages
|
||||
give
|
||||
contact
|
||||
terms
|
||||
safeguarding
|
||||
custom
|
||||
}
|
||||
|
||||
enum MessageSource {
|
||||
youtube_feed
|
||||
youtube
|
||||
spotify
|
||||
}
|
||||
|
||||
/// The site's design in the working copy (one row, id 1): template, section variants, homepage
|
||||
/// order and the Website-only style settings (src/site/variants.ts). Fonts and corners are shared.
|
||||
model SiteDesign {
|
||||
id Int @id @default(1)
|
||||
template String
|
||||
variants Json
|
||||
home Json
|
||||
style Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
}
|
||||
|
||||
/// A page: the fixed ones (§6) and custom pages built from blocks.
|
||||
model Page {
|
||||
id String @id @default(uuid())
|
||||
kind PageKind
|
||||
slug String @unique
|
||||
title String
|
||||
/// Per-page SEO (ROADMAP-v3 §11); null uses the generated one.
|
||||
seoTitle String?
|
||||
description String?
|
||||
navLabel String?
|
||||
inNav Boolean @default(true)
|
||||
position Int @default(0)
|
||||
imageId String?
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
sections Section[]
|
||||
|
||||
@@index([kind])
|
||||
}
|
||||
|
||||
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
|
||||
/// is one of that type's ids. Content is never tied to a template (§2).
|
||||
model Section {
|
||||
id String @id @default(uuid())
|
||||
pageId String
|
||||
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
|
||||
type String
|
||||
variant String?
|
||||
position Int @default(0)
|
||||
hidden Boolean @default(false)
|
||||
data Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([pageId, position])
|
||||
}
|
||||
|
||||
model Ministry {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
name String
|
||||
summary String?
|
||||
body String?
|
||||
imageId String?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
leaders WebsiteUser[]
|
||||
}
|
||||
|
||||
model Leader {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
role String?
|
||||
bio String?
|
||||
photoId String?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
}
|
||||
|
||||
model MessageSeries {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
summary String?
|
||||
imageId String?
|
||||
createdAt DateTime @default(now())
|
||||
messages Message[]
|
||||
}
|
||||
|
||||
/// A message (sermon), from the YouTube feed or added by hand (§7). Published on its own, not with
|
||||
/// the site's Publish (decision 9). Audio and video are linked, never uploaded.
|
||||
model Message {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
date DateTime
|
||||
source MessageSource
|
||||
mediaUrl String
|
||||
/// The YouTube video id or Spotify episode id: one message per video, whichever way it came in.
|
||||
externalId String? @unique
|
||||
thumbnailUrl String?
|
||||
speaker String?
|
||||
passage String?
|
||||
notes String?
|
||||
seriesId String?
|
||||
series MessageSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
|
||||
hidden Boolean @default(false)
|
||||
publishedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([date])
|
||||
}
|
||||
|
||||
/// A simple event made in the Website (§8). Registrations and payments are only Cross Events'.
|
||||
model SimpleEvent {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
startsAt DateTime
|
||||
endsAt DateTime?
|
||||
allDay Boolean @default(false)
|
||||
timezone String @default("Africa/Johannesburg")
|
||||
location String?
|
||||
description String?
|
||||
imageId String?
|
||||
link String?
|
||||
cancelled Boolean @default(false)
|
||||
publishedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([startsAt])
|
||||
}
|
||||
|
||||
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4).
|
||||
model ImportedEvent {
|
||||
id String @id @default(uuid())
|
||||
originProduct String
|
||||
originId String
|
||||
startsAt DateTime
|
||||
data Json
|
||||
syncedAt DateTime @default(now())
|
||||
|
||||
@@unique([originProduct, originId])
|
||||
@@index([startsAt])
|
||||
}
|
||||
|
||||
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
|
||||
/// published versions use it.
|
||||
model MediaAsset {
|
||||
id String @id @default(uuid())
|
||||
filename String
|
||||
mime String
|
||||
bytes Int
|
||||
width Int?
|
||||
height Int?
|
||||
alt String @default("")
|
||||
/// The resized files (WebP and JPEG per width) and their sizes, counted with `bytes`.
|
||||
sizes Json?
|
||||
uploadedBy String?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A published version: an immutable snapshot of the working copy (§4). Restore copies one back.
|
||||
model SiteVersion {
|
||||
id String @id @default(uuid())
|
||||
number Int @unique
|
||||
snapshot Json
|
||||
note String?
|
||||
publishedBy String
|
||||
publishedAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked.
|
||||
model PreviewLink {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
createdBy String
|
||||
createdAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
revokedAt DateTime?
|
||||
}
|
||||
|
||||
/// Someone who can use the admin: keyed by their account's `sub` from Accounts.
|
||||
model WebsiteUser {
|
||||
id String @id
|
||||
email String
|
||||
name String
|
||||
role WebsiteRole
|
||||
/// A Ministry leader edits only their own ministry.
|
||||
ministryId String?
|
||||
ministry Ministry? @relation(fields: [ministryId], references: [id], onDelete: SetNull)
|
||||
lastSignInAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A signed-in admin session (the `ccw_session` cookie holds the token; only its SHA-256 is kept).
|
||||
/// `sid` is Accounts' session id, so a back-channel logout ends the matching sessions.
|
||||
model Session {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
userId String
|
||||
sid String?
|
||||
/// Whether Accounts did a second step for this sign-in (`amr` has `mfa`).
|
||||
mfa Boolean @default(false)
|
||||
/// The ID token (encrypted), for "Sign out" at Accounts (`id_token_hint`).
|
||||
idToken String?
|
||||
createdAt DateTime @default(now())
|
||||
lastSeenAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
|
||||
@@index([userId])
|
||||
@@index([sid])
|
||||
}
|
||||
|
||||
/// A link to another of the church's products (`crosscode.link/1`, as Events 2.4): Accounts, for
|
||||
/// signing in, and Events / the App for the event feed. The secret is encrypted.
|
||||
model ProductLink {
|
||||
installId String @id
|
||||
product String
|
||||
url String
|
||||
publicKey String
|
||||
secret String
|
||||
connectedAt DateTime @default(now())
|
||||
connectedById String?
|
||||
lastSyncError String?
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
/// Nonces of link messages seen in the last hour (replays are refused).
|
||||
model LinkNonce {
|
||||
nonce String @id
|
||||
seenAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
actorId String?
|
||||
actorRole String
|
||||
action String
|
||||
targetType String
|
||||
targetId String?
|
||||
metadata Json?
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model AppSetting {
|
||||
key String @id
|
||||
value String
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* The Website's part of a church's export (`crosscode export` / uninstall): `export.json` in
|
||||
* --out-dir (src/export/churchExport.ts). The crosscode script adds the uploads next to it.
|
||||
*
|
||||
* npx tsx scripts/export-church.ts --out-dir <dir>
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { buildExport } from '../src/export/churchExport.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
|
||||
const i = process.argv.indexOf('--out-dir');
|
||||
const out = i > 0 ? process.argv[i + 1] : null;
|
||||
if (!out) {
|
||||
console.error('Usage: export-church.ts --out-dir <dir>');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const data = await buildExport(createCtx(loadConfig(), db));
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
fs.writeFileSync(path.join(out, 'export.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
|
||||
console.log(` export.json: ${data.website!.pages.length} pages, ${data.website!.messages.length} messages, ${data.files.length} files`);
|
||||
await db.$disconnect();
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The Express app (docs/WEBSITE-1.0-PLAN.md §1). Everything is under /api, so the site and its API
|
||||
* share one address (as Events and Accounts): nginx sends /api to this backend and the rest to Next.js.
|
||||
*
|
||||
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
|
||||
* /api/v1/site/… the public site (what visitors see: the latest published version)
|
||||
* /api/auth/… signing in to the admin through the church's Accounts
|
||||
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
|
||||
* /api/links/v1/… Connect and Disconnect with the church's other products
|
||||
* /api/v1/admin/… the admin (signed in, by role)
|
||||
*
|
||||
* To come (§1): the admin's content, publish and preview links, /api/uploads/…, the event feed.
|
||||
*/
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { authRouter } from './auth/routes.js';
|
||||
import { requireRole } from './auth/sessions.js';
|
||||
import { dbUp } from './hub/client.js';
|
||||
import { ApiError, handle, sendError } from './http.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
import { linksRouter } from './links/routes.js';
|
||||
import { siteStatus } from './site/status.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
|
||||
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
// The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11).
|
||||
res.setHeader('X-Robots-Tag', 'noindex');
|
||||
next();
|
||||
});
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
const db = await dbUp(ctx);
|
||||
res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'website', version: appVersion(), db });
|
||||
});
|
||||
|
||||
const site = express.Router();
|
||||
site.get('/status', handle(() => siteStatus(ctx)));
|
||||
app.use('/api/v1/site', site);
|
||||
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
|
||||
const admin = express.Router();
|
||||
admin.use(express.json({ limit: '256kb' }));
|
||||
admin.use(requireRole(ctx, 'viewer'));
|
||||
admin.get('/me', handle(async (req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
|
||||
app.use('/api/v1/admin', admin);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
|
||||
});
|
||||
|
||||
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
if (res.headersSent) return next(err);
|
||||
const e = err as { type?: string };
|
||||
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
|
||||
return sendError(res, err);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The church's Accounts, as this site's OIDC client (WEBSITE-1.0-PLAN §1, §10), built on
|
||||
* `@crosscode/auth-client` from the Accounts link (links/connect.ts). Its address is the one the
|
||||
* Hub listed; the client id is this site's Hub install id and the client secret comes from the
|
||||
* link's secret, so there's no `.env` setting for any of it (as Cross Events 3.x).
|
||||
*/
|
||||
import type * as AuthClient from '@crosscode/auth-client';
|
||||
import type { AccountsClient } from '@crosscode/auth-client';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
|
||||
export type AuthClientModule = typeof AuthClient;
|
||||
|
||||
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
|
||||
|
||||
export class AccountsUnavailable extends ApiError {
|
||||
constructor(message: string) {
|
||||
super(503, 'ACCOUNTS_UNAVAILABLE', message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The Accounts link, or null while the Website isn't linked to Accounts. */
|
||||
export async function accountsLink(ctx: Ctx) {
|
||||
return ctx.db.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
|
||||
}
|
||||
|
||||
const cache = new WeakMap<Ctx, { key: string; client: Promise<AccountsClient> }>();
|
||||
|
||||
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
|
||||
export async function accounts(ctx: Ctx): Promise<AccountsClient> {
|
||||
const link = await accountsLink(ctx);
|
||||
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet. It links by itself within 15 minutes of being installed.');
|
||||
const clientId = await ctx.settings.get('hub_install_id');
|
||||
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.');
|
||||
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
|
||||
let hit = cache.get(ctx);
|
||||
if (!hit || hit.key !== key) {
|
||||
const client = ctx.authClient().then((m) => m.accountsClient({
|
||||
accountsUrl: link.url,
|
||||
productUrl: ctx.config.publicUrl,
|
||||
clientId,
|
||||
linkSecret: ctx.secrets.decrypt(link.secret),
|
||||
allowInsecure: !ctx.config.production && link.url.startsWith('http:'),
|
||||
}));
|
||||
// A failed discovery (Accounts down for a moment) is tried again next time.
|
||||
client.catch(() => { if (cache.get(ctx)?.key === key) cache.delete(ctx); });
|
||||
hit = { key, client };
|
||||
cache.set(ctx, hit);
|
||||
}
|
||||
try {
|
||||
return await hit.client;
|
||||
} catch (e) {
|
||||
throw new AccountsUnavailable(`The church's Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Signing in to the Website's admin through the church's Accounts (WEBSITE-1.0-PLAN §10, as Cross
|
||||
* Events 3.x), under /api:
|
||||
*
|
||||
* GET /auth/signin?returnTo=…[&mfa=1] PKCE + state in a short-lived cookie, then off to Accounts
|
||||
* GET /auth/callback back from Accounts: the Website's own session, then returnTo
|
||||
* GET /auth/me who's signed in (the admin pages ask)
|
||||
* POST /auth/signout ends this session, then Accounts' sign-out (all the church's sites)
|
||||
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
|
||||
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
|
||||
*
|
||||
* Who may use the admin is the Website's own business (roles are never in the claims). The first
|
||||
* Owner is whoever signs in with the church's admin email from the Hub (HUB_ADMIN_EMAIL), verified
|
||||
* in Accounts, while the site has no Owner; everyone else is added by an Owner or Admin.
|
||||
*/
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { WebsiteRole } from '../generated/prisma/client.js';
|
||||
import { handle, sendError } from '../http.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { accounts, AccountsUnavailable } from './accounts.js';
|
||||
import { cookieOptions, currentSession, needsTwoFactor, readCookies, SESSION_COOKIE, startSession } from './sessions.js';
|
||||
|
||||
const PENDING_COOKIE = 'ccw_signin';
|
||||
const MFA_COOKIE = 'ccw_signin_mfa';
|
||||
const COOKIE_PATH = '/api/auth';
|
||||
const PENDING_MINUTES = 10;
|
||||
|
||||
/** A page of this site, absolute (in development the API and the pages are on different ports). */
|
||||
const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${path}`;
|
||||
|
||||
/** The problem page: a short reason and "Try again" with the same return path. */
|
||||
const problem = (ctx: Ctx, res: Response, code: string, returnTo = '/admin') =>
|
||||
res.redirect(303, page(ctx, `/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
|
||||
|
||||
type UserRow = { id: string; name: string; email: string; role: WebsiteRole };
|
||||
|
||||
/**
|
||||
* The Website user for a sign-in: by `sub`; else the first Owner, when the site has none and this is
|
||||
* the Hub's admin email (verified); else nobody (no access to this admin).
|
||||
*/
|
||||
export async function userForClaims(ctx: Ctx, claims: IdentityClaims): Promise<{ user: UserRow | null; created?: boolean }> {
|
||||
const known = await ctx.db.websiteUser.findUnique({ where: { id: claims.sub } });
|
||||
if (known) {
|
||||
const user = await ctx.db.websiteUser.update({ where: { id: known.id }, data: { name: claims.name, email: claims.email.toLowerCase(), lastSignInAt: ctx.now() } });
|
||||
return { user };
|
||||
}
|
||||
const adminEmail = ctx.config.hubAdminEmail;
|
||||
if (!adminEmail || !claims.email_verified || claims.email.toLowerCase() !== adminEmail) return { user: null };
|
||||
if (await ctx.db.websiteUser.findFirst({ where: { role: 'owner' } })) return { user: null };
|
||||
const user = await ctx.db.websiteUser.create({
|
||||
data: { id: claims.sub, name: claims.name, email: claims.email.toLowerCase(), role: 'owner', lastSignInAt: ctx.now() },
|
||||
});
|
||||
return { user, created: true };
|
||||
}
|
||||
|
||||
export function authRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
|
||||
r.get('/auth/signin', async (req, res) => {
|
||||
const returnTo = safeReturnPath(req.query.returnTo);
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const requireTwoFactor = req.query.mfa === '1';
|
||||
const { url, cookie } = await auth.startSignIn(returnTo, { requireTwoFactor });
|
||||
const opts = { ...cookieOptions(ctx, COOKIE_PATH), maxAge: PENDING_MINUTES * 60e3 };
|
||||
res.cookie(PENDING_COOKIE, cookie, opts);
|
||||
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', opts);
|
||||
else res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
return res.redirect(303, url);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE', returnTo);
|
||||
console.error('[auth] Starting a sign-in failed:', e);
|
||||
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
|
||||
}
|
||||
});
|
||||
|
||||
r.get(OIDC_CLIENT_PATHS.callback.replace(/^\/api/, ''), async (req, res) => {
|
||||
const cookies = readCookies(req);
|
||||
const askedForTwoFactor = cookies[MFA_COOKIE] === '1';
|
||||
res.clearCookie(PENDING_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
let result: Awaited<ReturnType<Awaited<ReturnType<typeof accounts>>['finishSignIn']>>;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
result = await auth.finishSignIn(new URL(req.originalUrl, ctx.config.publicUrl), cookies[PENDING_COOKIE]);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE');
|
||||
const code = (e as { code?: string }).code;
|
||||
// The person pressed Cancel at Accounts, or the pending cookie expired.
|
||||
if (req.query.error === 'access_denied') return res.redirect(303, page(ctx, '/'));
|
||||
return problem(ctx, res, code === 'NO_PENDING' ? 'EXPIRED' : 'SIGNIN_FAILED');
|
||||
}
|
||||
const { claims, returnTo, idToken } = result;
|
||||
const { user, created } = await userForClaims(ctx, claims);
|
||||
if (!user) {
|
||||
await audit(ctx, { actorId: claims.sub, actorRole: 'none', action: 'admin_sign_in_refused', targetType: 'website_user', targetId: claims.sub, ip: clientIp(req) });
|
||||
return problem(ctx, res, 'NO_ACCESS', returnTo);
|
||||
}
|
||||
const mfa = claims.amr.includes('mfa');
|
||||
if (!mfa && (await needsTwoFactor(ctx, user.role))) {
|
||||
// Once: ask Accounts again with a second step. If it still comes back without one, say why.
|
||||
if (askedForTwoFactor) return problem(ctx, res, 'TWO_FACTOR_NEEDED', returnTo);
|
||||
return res.redirect(303, page(ctx, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`));
|
||||
}
|
||||
// Accounts' session id, when its token carries one (not part of crosscode.identity/1's claims).
|
||||
const sid = (claims as unknown as { sid?: string }).sid ?? null;
|
||||
await startSession(ctx, res, { userId: user.id, sid, mfa, idToken });
|
||||
await audit(ctx, { actorId: user.id, actorRole: user.role, action: created ? 'first_owner_signed_in' : 'admin_signed_in', targetType: 'website_user', targetId: user.id, ip: clientIp(req) });
|
||||
return res.redirect(303, page(ctx, returnTo));
|
||||
});
|
||||
|
||||
r.get('/auth/me', handle(async (req, res) => {
|
||||
const s = await currentSession(ctx, req);
|
||||
if (!s) {
|
||||
res.status(401).json({ error: { code: 'SIGNED_OUT', message: 'Please sign in.' } });
|
||||
return undefined;
|
||||
}
|
||||
return { user: s.user, mfa: s.mfa };
|
||||
}));
|
||||
|
||||
r.post('/auth/signout', async (req, res) => {
|
||||
const s = await currentSession(ctx, req).catch(() => null);
|
||||
res.clearCookie(SESSION_COOKIE, cookieOptions(ctx));
|
||||
if (s) {
|
||||
await ctx.db.session.delete({ where: { id: s.sessionId } }).catch(() => {});
|
||||
await audit(ctx, { actorId: s.user.id, actorRole: s.user.role, action: 'admin_signed_out', targetType: 'website_user', targetId: s.user.id, ip: clientIp(req) });
|
||||
}
|
||||
// Then Accounts, so the person is signed out of all the church's sites and comes back here.
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
return res.redirect(303, auth.signOutUrl(s?.idToken ?? undefined));
|
||||
} catch {
|
||||
return res.redirect(303, page(ctx, '/'));
|
||||
}
|
||||
});
|
||||
|
||||
r.post(OIDC_CLIENT_PATHS.backchannelLogout.replace(/^\/api/, ''), express.urlencoded({ extended: false, limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const { sub, sid } = await auth.verifyLogoutToken(String(req.body?.logout_token ?? ''));
|
||||
// That Accounts session's sign-ins here, and any whose session id wasn't known.
|
||||
await ctx.db.session.deleteMany({ where: sid ? { userId: sub, OR: [{ sid }, { sid: null }] } : { userId: sub } });
|
||||
res.set('Cache-Control', 'no-store').status(200).end();
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code;
|
||||
res.status(code === 'BAD_TOKEN' ? 400 : 503).json({ error: 'invalid_request' });
|
||||
}
|
||||
});
|
||||
|
||||
r.post(ACCOUNTS_CALL_PATH.replace(/^\/api/, ''), express.raw({ type: '*/*', limit: '256kb' }), async (req, res) => {
|
||||
let call: AccountsCall;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
call = auth.verifyAccountsCall(req.body as Buffer, req.headers);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return sendError(res, e);
|
||||
return res.status(401).json({ error: { code: (e as { code?: string }).code ?? 'BAD_SIGNATURE', message: (e as Error).message } });
|
||||
}
|
||||
try {
|
||||
return res.json(await handleAccountsCall(ctx, call, req));
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accounts' signed calls. The Website only keeps an admin's name, email and role, so: update the
|
||||
* copy, export it, or remove the person (and their sessions). Someone the Website doesn't know is
|
||||
* answered as done.
|
||||
*/
|
||||
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
|
||||
const user = await ctx.db.websiteUser.findUnique({ where: { id: call.sub } });
|
||||
switch (call.type) {
|
||||
case 'user.updated': {
|
||||
if (user) await ctx.db.websiteUser.update({ where: { id: user.id }, data: { name: call.profile.name, email: call.profile.email.toLowerCase() } });
|
||||
return { schema: IDENTITY_SCHEMA, ok: true };
|
||||
}
|
||||
case 'user.export': {
|
||||
const reply: UserExportReply = {
|
||||
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'website', generatedAt: ctx.now().toISOString(),
|
||||
sections: user ? [{
|
||||
key: 'website_admin',
|
||||
title: 'Your access to the church\'s website admin',
|
||||
records: [{ name: user.name, email: user.email, role: user.role, since: user.createdAt.toISOString(), lastSignIn: user.lastSignInAt?.toISOString() ?? null }],
|
||||
}] : [],
|
||||
};
|
||||
return reply;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
if (user) {
|
||||
await ctx.db.session.deleteMany({ where: { userId: user.id } });
|
||||
await ctx.db.websiteUser.delete({ where: { id: user.id } });
|
||||
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'website_user_deleted', targetType: 'website_user', targetId: user.id, metadata: { role: user.role }, ip: clientIp(req) });
|
||||
}
|
||||
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Admin sessions and roles (WEBSITE-1.0-PLAN §10). The Website keeps its own session after a
|
||||
* sign-in through Accounts: an HttpOnly cookie with a random token, of which only the SHA-256 is
|
||||
* stored. Roles are the Website's own (keyed by the account's `sub`); Accounts never says them.
|
||||
*/
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { WebsiteRole } from '../generated/prisma/client.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
|
||||
export const SESSION_COOKIE = 'ccw_session';
|
||||
|
||||
/** Lowest to highest. A role can do what every role before it can. */
|
||||
export const ROLES: readonly WebsiteRole[] = ['viewer', 'ministry_leader', 'editor', 'admin', 'owner'];
|
||||
export const atLeast = (role: WebsiteRole, min: WebsiteRole) => ROLES.indexOf(role) >= ROLES.indexOf(min);
|
||||
|
||||
/** Roles that need a second step at sign-in (on by default, §10; AppSetting `two_factor_required_for_admins`). */
|
||||
export async function needsTwoFactor(ctx: Ctx, role: WebsiteRole): Promise<boolean> {
|
||||
return atLeast(role, 'admin') && (await ctx.settings.bool('two_factor_required_for_admins', true));
|
||||
}
|
||||
|
||||
export function readCookies(req: Request): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of String(req.headers.cookie || '').split(';')) {
|
||||
const i = part.indexOf('=');
|
||||
if (i > 0) {
|
||||
try {
|
||||
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
||||
} catch {
|
||||
// A cookie this site didn't write: ignored.
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieOptions = (ctx: Ctx, path = '/') => ({ httpOnly: true, sameSite: 'lax' as const, secure: ctx.config.production, path });
|
||||
|
||||
export async function startSession(ctx: Ctx, res: Response, s: { userId: string; sid: string | null; mfa: boolean; idToken: string }) {
|
||||
const token = randomToken();
|
||||
const now = ctx.now();
|
||||
const expiresAt = new Date(now.getTime() + ctx.config.sessionDays * 24 * 3600e3);
|
||||
await ctx.db.session.create({
|
||||
data: { tokenHash: hashToken(token), userId: s.userId, sid: s.sid, mfa: s.mfa, idToken: ctx.secrets.encrypt(s.idToken), createdAt: now, lastSeenAt: now, expiresAt },
|
||||
});
|
||||
res.cookie(SESSION_COOKIE, token, { ...cookieOptions(ctx), expires: expiresAt });
|
||||
}
|
||||
|
||||
export type Signed = {
|
||||
sessionId: string;
|
||||
idToken: string | null;
|
||||
mfa: boolean;
|
||||
user: { id: string; name: string; email: string; role: WebsiteRole; ministryId: string | null };
|
||||
};
|
||||
|
||||
/** The signed-in admin for this request, or null. */
|
||||
export async function currentSession(ctx: Ctx, req: Request): Promise<Signed | null> {
|
||||
const token = readCookies(req)[SESSION_COOKIE];
|
||||
if (!token) return null;
|
||||
const session = await ctx.db.session.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
if (!session) return null;
|
||||
const now = ctx.now();
|
||||
if (session.expiresAt <= now) {
|
||||
await ctx.db.session.delete({ where: { id: session.id } }).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
const user = await ctx.db.websiteUser.findUnique({ where: { id: session.userId } });
|
||||
if (!user) return null;
|
||||
// Seen at most once a minute, so reading pages doesn't write on every request.
|
||||
if (now.getTime() - session.lastSeenAt.getTime() > 60_000) {
|
||||
await ctx.db.session.update({ where: { id: session.id }, data: { lastSeenAt: now } }).catch(() => {});
|
||||
}
|
||||
let idToken: string | null;
|
||||
try {
|
||||
idToken = session.idToken ? ctx.secrets.decrypt(session.idToken) : null;
|
||||
} catch {
|
||||
idToken = null;
|
||||
}
|
||||
return {
|
||||
sessionId: session.id,
|
||||
idToken,
|
||||
mfa: session.mfa,
|
||||
user: { id: user.id, name: user.name, email: user.email, role: user.role, ministryId: user.ministryId },
|
||||
};
|
||||
}
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
signed?: Signed;
|
||||
}
|
||||
}
|
||||
|
||||
/** Only signed-in admins with at least `min`. 401 when signed out, 403 when the role is too low. */
|
||||
export function requireRole(ctx: Ctx, min: WebsiteRole = 'viewer'): RequestHandler {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
currentSession(ctx, req).then((s) => {
|
||||
if (!s) return next(new ApiError(401, 'SIGNED_OUT', 'Please sign in.'));
|
||||
if (!atLeast(s.user.role, min)) return next(new ApiError(403, 'FORBIDDEN', 'Your role on this website can\'t do that.'));
|
||||
req.signed = s;
|
||||
return next();
|
||||
}).catch(next);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
|
||||
* whole app against an in-memory database and a stand-in Accounts (tests/support/).
|
||||
*/
|
||||
import type { PrismaClient } from './generated/prisma/client.js';
|
||||
import type { Config } from './lib/config.js';
|
||||
import { Secrets } from './lib/crypto.js';
|
||||
import { Settings } from './lib/settings.js';
|
||||
import { loadAuthClient, type AuthClientModule } from './auth/accounts.js';
|
||||
|
||||
export type Db = PrismaClient;
|
||||
|
||||
export type Ctx = {
|
||||
config: Config;
|
||||
db: Db;
|
||||
secrets: Secrets;
|
||||
settings: Settings;
|
||||
/** `@crosscode/auth-client` (tests give a stand-in). */
|
||||
authClient: () => Promise<AuthClientModule>;
|
||||
now: () => Date;
|
||||
};
|
||||
|
||||
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule> } = {}): Ctx {
|
||||
const secrets = new Secrets(config.secret);
|
||||
const partial = { config, db, secrets } as Ctx;
|
||||
partial.settings = new Settings(partial);
|
||||
partial.authClient = opts.authClient ?? loadAuthClient;
|
||||
partial.now = opts.now ?? (() => new Date());
|
||||
return partial;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* The Website's part of a church's export when it leaves (`crosscode export` / uninstall,
|
||||
* WEBSITE-1.0-PLAN §11): `crosscode.church-export/1` with its `website` part, in plain terms and
|
||||
* our own field names (no table names or internal ids; records refer to each other by refs made
|
||||
* for the export). The uploads are copied next to it by the crosscode script (`uploads/`).
|
||||
*
|
||||
* The content is the working copy, including changes not yet published, as the admins left it.
|
||||
*/
|
||||
import { churchExportSchema, type ChurchExport, type ExportWebsite, type WebsiteTemplate, WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
|
||||
const iso = (d: Date | null | undefined) => (d ? d.toISOString() : null);
|
||||
const uploadPath = (filename: string) => `uploads/${filename.replace(/[^A-Za-z0-9._/-]/g, '-')}`;
|
||||
const ROLE_NAMES: Record<string, string> = { owner: 'website owner', admin: 'website admin', editor: 'website editor', ministry_leader: 'ministry leader', viewer: 'website viewer' };
|
||||
|
||||
export async function buildExport(ctx: Ctx): Promise<ChurchExport> {
|
||||
const db = ctx.db;
|
||||
const [design, pages, messages, events, versions, media, users] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.message.findMany({ orderBy: { date: 'asc' }, include: { series: true } }),
|
||||
db.simpleEvent.findMany({ orderBy: { startsAt: 'asc' } }),
|
||||
db.siteVersion.findMany({ orderBy: { number: 'asc' } }),
|
||||
db.mediaAsset.findMany({ orderBy: { createdAt: 'asc' } }),
|
||||
db.websiteUser.findMany({ orderBy: { name: 'asc' } }),
|
||||
]);
|
||||
const mediaPath = new Map(media.map((m) => [m.id, uploadPath(m.filename)]));
|
||||
const names = new Map(users.map((u) => [u.id, u.name]));
|
||||
const template: WebsiteTemplate = (WEBSITE_TEMPLATES as readonly string[]).includes(design?.template ?? '') ? (design!.template as WebsiteTemplate) : 'heritage';
|
||||
|
||||
const website: ExportWebsite = {
|
||||
template,
|
||||
firstPublishedAt: iso(versions[0]?.publishedAt),
|
||||
style: Object.fromEntries(Object.entries((design?.style ?? {}) as Record<string, unknown>).filter(([, v]) => typeof v === 'string')) as Record<string, string>,
|
||||
pages: pages.map((p, n) => ({
|
||||
ref: `g${n + 1}`,
|
||||
title: p.title,
|
||||
path: p.kind === 'home' ? '/' : `/${p.slug}`,
|
||||
kind: p.kind,
|
||||
inNavigation: p.inNav,
|
||||
seo: { title: p.seoTitle, description: p.description },
|
||||
sections: p.sections.map((s) => ({ type: s.type, variant: s.variant ?? '', hidden: s.hidden, content: (s.data ?? {}) as Record<string, never> })),
|
||||
})),
|
||||
messages: messages.map((m, n) => ({
|
||||
ref: `m${n + 1}`, title: m.title, date: iso(m.date), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage, notes: m.notes,
|
||||
url: m.mediaUrl, source: m.source === 'youtube_feed' ? 'youtube-feed' as const : 'manual' as const, hidden: m.hidden,
|
||||
})),
|
||||
events: events.map((e, n) => ({
|
||||
ref: `w${n + 1}`, title: e.title, description: e.description, startsAt: iso(e.startsAt), endsAt: iso(e.endsAt), location: e.location,
|
||||
link: e.link, image: e.imageId ? mediaPath.get(e.imageId) ?? null : null, published: e.publishedAt !== null,
|
||||
})),
|
||||
versions: versions.map((v) => ({ number: v.number, publishedAt: iso(v.publishedAt), by: names.get(v.publishedBy) ?? null, note: v.note })),
|
||||
media: media.map((m) => ({ path: uploadPath(m.filename), alt: m.alt || null, caption: null })),
|
||||
};
|
||||
|
||||
return churchExportSchema.parse({
|
||||
schema: 'crosscode.church-export/1',
|
||||
exportedAt: ctx.now().toISOString(),
|
||||
product: 'website',
|
||||
productVersion: appVersion(),
|
||||
church: { name: (await ctx.settings.get('church_name')) || 'Church Website', timezone: ctx.config.timezone },
|
||||
people: users.map((u, n) => ({
|
||||
ref: `p${n + 1}`, name: u.name, email: u.email, phone: null, role: ROLE_NAMES[u.role] ?? u.role, createdAt: iso(u.createdAt),
|
||||
consent: { email: null, whatsapp: null, privacyNoticeAcceptedAt: null },
|
||||
})),
|
||||
events: [], registrations: [], payments: [], checkIns: [], rosters: [],
|
||||
settings: { address: ctx.config.publicUrl },
|
||||
files: media.map((m) => ({ path: uploadPath(m.filename), bytes: m.bytes })),
|
||||
website,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
|
||||
* Events' /api/v2) and async handlers.
|
||||
*/
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Known errors carry a status and code; anything else is a 500. */
|
||||
export function sendError(res: Response, e: unknown) {
|
||||
if (e instanceof ApiError) {
|
||||
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
|
||||
}
|
||||
console.error('[api]', e);
|
||||
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
||||
}
|
||||
|
||||
export const handle = (fn: (req: Request, res: Response) => Promise<unknown>): RequestHandler => (req, res) => {
|
||||
fn(req, res).then((out) => {
|
||||
if (out !== undefined && !res.headersSent) res.json(out);
|
||||
}).catch((e) => sendError(res, e));
|
||||
};
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* The Website and the Hub (docs/hub-protocol.md §6, protocol v2, product `website`), as Accounts'
|
||||
* hub/client.ts: register with a `CCW-` licence key (by itself from HUB_LICENCE_KEY on a Hub
|
||||
* install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's
|
||||
* `linkedProducts` (the church's other installs) is cached for Connect, and the Website connects
|
||||
* itself to the church's Accounts once the Hub lists it (links/connect.ts).
|
||||
*
|
||||
* The install id the Hub gives is also this site's OIDC client id at Accounts.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
import { connectAccountsIfListed } from '../links/connect.js';
|
||||
import { keyPair, saveLinkedProducts } from '../links/store.js';
|
||||
import { hubPublicKey, verifyToken } from './licence.js';
|
||||
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
const TIMEOUT_MS = 15000;
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const STARTED_AT = Date.now();
|
||||
/** 5 GB included (ROADMAP-v3 §10); the licence's `limits.storageBytes` says more when steps were bought. */
|
||||
export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3;
|
||||
|
||||
export class HubError extends Error {
|
||||
constructor(message: string, public code: string, public status: number) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
|
||||
const raw = JSON.stringify(body);
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (sign) {
|
||||
const timestamp = ctx.now().toISOString();
|
||||
headers['X-Hub-Install'] = sign.installId;
|
||||
headers['X-Hub-Timestamp'] = timestamp;
|
||||
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
|
||||
}
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
} catch (e) {
|
||||
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function dbUp(ctx: Ctx): Promise<boolean> {
|
||||
try {
|
||||
await ctx.db.$queryRaw`SELECT 1`;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function health(ctx: Ctx) {
|
||||
return {
|
||||
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||
db: await dbUp(ctx),
|
||||
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
|
||||
lastBackupAt: null,
|
||||
disk: null,
|
||||
errorsLast24h: null,
|
||||
pendingMigrations: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Aggregate counts only (hub.websiteStatsSchema): never anyone's details. */
|
||||
export async function stats(ctx: Ctx) {
|
||||
const now = ctx.now();
|
||||
const since = new Date(now.getTime() - 30 * DAY);
|
||||
const [published, drafts, total, last30d, upcomingSimple, imported, editors, media] = await Promise.all([
|
||||
ctx.db.siteVersion.count(),
|
||||
ctx.db.page.count({ where: { archivedAt: null } }),
|
||||
ctx.db.message.count({ where: { hidden: false } }),
|
||||
ctx.db.message.count({ where: { hidden: false, date: { gte: since } } }),
|
||||
ctx.db.simpleEvent.count({ where: { startsAt: { gte: now }, publishedAt: { not: null } } }),
|
||||
ctx.db.importedEvent.count({ where: { startsAt: { gte: now } } }),
|
||||
ctx.db.websiteUser.count({ where: { role: { not: 'viewer' } } }),
|
||||
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
|
||||
]);
|
||||
return {
|
||||
// Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions).
|
||||
pages: { published: published > 0 ? drafts : 0, drafts: published > 0 ? 0 : drafts },
|
||||
messages: { total, last30d },
|
||||
events: { upcomingSimple, imported },
|
||||
editors,
|
||||
storage: { usedBytes: media._sum.bytes ?? 0, includedBytes: INCLUDED_STORAGE_BYTES },
|
||||
};
|
||||
}
|
||||
|
||||
/** Register with a licence key (HUB_LICENCE_KEY). */
|
||||
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
|
||||
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('WEBSITE_URL isn\'t set.', 'NO_SITE_URL', 400);
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
licenceKey: licenceKey.trim().toUpperCase(),
|
||||
product: 'website',
|
||||
install: {
|
||||
name: 'Website',
|
||||
url: ctx.config.publicUrl,
|
||||
adminContact,
|
||||
version: appVersion(),
|
||||
timezone: ctx.config.timezone,
|
||||
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
|
||||
features: {},
|
||||
publicKey: publicKeyPem,
|
||||
},
|
||||
};
|
||||
const check = hub.registerRequestSchema.safeParse(body);
|
||||
if (!check.success) throw new HubError('That doesn\'t look like a Website licence key (CCW-…).', 'INVALID_REQUEST', 400);
|
||||
const data = await post(ctx, '/api/installs/register', check.data);
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: String(data.installId),
|
||||
hub_install_secret: String(data.installSecret),
|
||||
hub_licence: String(data.licence),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
hub_public_key_status: 'matches',
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return claims;
|
||||
}
|
||||
|
||||
/** The heartbeat (every 15 minutes). Skips quietly when not connected. */
|
||||
export async function heartbeat(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
const secret = await ctx.settings.get('hub_install_secret');
|
||||
if (!installId || !secret) return { skipped: 'not connected' };
|
||||
const status = await ctx.settings.get('hub_public_key_status');
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
product: 'website',
|
||||
version: appVersion(),
|
||||
health: await health(ctx),
|
||||
stats: await stats(ctx),
|
||||
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
|
||||
};
|
||||
try {
|
||||
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
await ctx.settings.setMany({
|
||||
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
|
||||
if (err.code === 'INSTALL_NOT_FOUND') {
|
||||
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
|
||||
return { ok: false, reconnect: true };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY. Never throws. */
|
||||
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
|
||||
const key = ctx.config.hubLicenceKey;
|
||||
if (!key) return { connected: false, reason: 'no_key' };
|
||||
for (let i = 1; i <= attempts; i++) {
|
||||
try {
|
||||
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
|
||||
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
|
||||
return { connected: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
|
||||
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
|
||||
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
|
||||
}
|
||||
}
|
||||
return { connected: false, reason: 'unreachable' };
|
||||
}
|
||||
|
||||
/** Heartbeats every 15 minutes until stopped (pg-boss comes with the Website's other jobs). */
|
||||
export function startHeartbeats(ctx: Ctx): () => void {
|
||||
if (!ctx.config.jobsEnabled) return () => {};
|
||||
const timer = setInterval(() => {
|
||||
heartbeat(ctx).catch((e) => console.warn('[hub] Heartbeat failed:', (e as Error).message));
|
||||
}, 15 * 60 * 1000);
|
||||
timer.unref?.();
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
|
||||
* key, as Cross Events does. A lapsed licence never takes the public site down (the Hub is never on the runtime path,
|
||||
* ROADMAP-v3 §1): admins see a banner.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
|
||||
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
|
||||
export function normalisePem(input: string | null | undefined): string | null {
|
||||
const text = String(input || '').replace(/\\n/g, '\n').trim();
|
||||
if (!text) return null;
|
||||
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
|
||||
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
|
||||
}
|
||||
|
||||
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
|
||||
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
export type LicenceClaims = {
|
||||
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
|
||||
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
|
||||
};
|
||||
|
||||
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
|
||||
if (!pem) return null;
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
|
||||
try {
|
||||
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
|
||||
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
|
||||
|
||||
/** The state for verified claims. Pure. */
|
||||
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
|
||||
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
|
||||
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
|
||||
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
|
||||
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
|
||||
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
|
||||
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
|
||||
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
|
||||
return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
}
|
||||
|
||||
export async function licenceStatus(ctx: Ctx) {
|
||||
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
|
||||
const claims = verifyToken(token, hubPublicKey(ctx));
|
||||
const valid = claims && claims.installId === installId ? claims : null;
|
||||
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
|
||||
}
|
||||
|
||||
/** The church's Hub customer id (the same for every product), once the licence says it. */
|
||||
export async function customerId(ctx: Ctx): Promise<string | null> {
|
||||
return (await licenceStatus(ctx)).claims?.customerId ?? null;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering
|
||||
* with the Hub from HUB_LICENCE_KEY, then heartbeats, which also link the site to the church's
|
||||
* Accounts once the Hub lists it. The other jobs (YouTube feed, storage count, sitemap, feed sync)
|
||||
* come with their features (docs/WEBSITE-1.0-PLAN.md §1).
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from './generated/prisma/client.js';
|
||||
import { createApp } from './app.js';
|
||||
import { createCtx } from './context.js';
|
||||
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
|
||||
import { loadConfig } from './lib/config.js';
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig();
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set.');
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
|
||||
const ctx = createCtx(config, db);
|
||||
const app = createApp(ctx);
|
||||
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
|
||||
const stopHeartbeats = startHeartbeats(ctx);
|
||||
|
||||
connectFromEnv(ctx).then((r) => {
|
||||
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
|
||||
}).catch(() => {});
|
||||
|
||||
const stop = async () => {
|
||||
stopHeartbeats();
|
||||
server.close();
|
||||
await db.$disconnect();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
process.on('SIGINT', stop);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('[website] Failed to start:', e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The admin audit log (who changed what, WEBSITE-1.0-PLAN §4). Logging never breaks the
|
||||
* action it records.
|
||||
*/
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export function clientIp(req: Request | undefined): string | null {
|
||||
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
|
||||
}
|
||||
|
||||
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
|
||||
try {
|
||||
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
|
||||
} catch (e) {
|
||||
console.error('[audit]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
|
||||
* tests pass their own with `loadConfig({...})`.
|
||||
*/
|
||||
export type TrustProxy = false | number | string | string[];
|
||||
|
||||
export type Config = {
|
||||
/** The public address, e.g. https://www.hopefamily.co.za (no trailing slash). */
|
||||
publicUrl: string;
|
||||
port: number;
|
||||
/** Signs preview links and cookies, encrypts stored secrets. Generated on the server, never sent anywhere. */
|
||||
secret: string;
|
||||
production: boolean;
|
||||
/** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */
|
||||
trustProxySetting: TrustProxy;
|
||||
hubUrl: string;
|
||||
hubLicenceKey: string | null;
|
||||
hubPublicKey: string | null;
|
||||
/** The church's contact from the Hub: the first person to sign in with this (verified) email becomes the Owner. */
|
||||
hubAdminName: string | null;
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
jobsEnabled: boolean;
|
||||
/** Where uploads go; default backend/uploads. */
|
||||
uploadDir: string | null;
|
||||
/** Local testing only: linked products (Accounts) on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
/** How long an admin stays signed in (days). */
|
||||
sessionDays: number;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
|
||||
/** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */
|
||||
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
|
||||
const raw = (v ?? '').trim();
|
||||
if (raw === '') return production ? 1 : false;
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'true') return 1;
|
||||
if (lower === 'false') return false;
|
||||
if (/^\d+$/.test(raw)) return Number(raw) || false;
|
||||
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
|
||||
}
|
||||
|
||||
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||
const production = env.NODE_ENV === 'production';
|
||||
const secret = env.WEBSITE_SECRET || '';
|
||||
if (production && secret.length < 32) throw new Error('WEBSITE_SECRET must be set (at least 32 characters) in production.');
|
||||
return {
|
||||
publicUrl: String(env.WEBSITE_URL || 'http://localhost:3300').replace(/\/+$/, ''),
|
||||
port: Number(env.PORT || 5300),
|
||||
secret: secret || 'development-only-secret-change-me-0123456789',
|
||||
production,
|
||||
trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production),
|
||||
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
|
||||
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
|
||||
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
|
||||
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
|
||||
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim().toLowerCase() || null,
|
||||
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
uploadDir: env.UPLOAD_DIR?.trim() || null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Secrets at rest (AES-256-GCM, as Accounts' lib/crypto.ts), and tokens. The key comes from
|
||||
* WEBSITE_SECRET; encrypted values start with "enc:".
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const SENTINEL = 'enc:';
|
||||
|
||||
export class Secrets {
|
||||
private readonly key: Buffer;
|
||||
|
||||
constructor(secret: string) {
|
||||
this.key = crypto.scryptSync(secret, 'crosscode-website-aes256gcm-v1', 32);
|
||||
}
|
||||
|
||||
encrypt(plain: string): string {
|
||||
if (plain.startsWith(SENTINEL)) return plain;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
|
||||
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
|
||||
}
|
||||
|
||||
/** Throws if the value was changed or encrypted with another key. */
|
||||
decrypt(value: string): string {
|
||||
if (!value.startsWith(SENTINEL)) return value;
|
||||
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
|
||||
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/** A random token for a cookie (32 bytes, base64url). */
|
||||
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
/** What's stored for a token: only its SHA-256. */
|
||||
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Site settings in `AppSetting` (key → string), as Accounts' lib/settings.ts. Secret ones are
|
||||
* encrypted at rest and never sent to the browser. A short cache keeps pages from reading the
|
||||
* table on every request.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']);
|
||||
|
||||
const TTL_MS = 30_000;
|
||||
|
||||
export class Settings {
|
||||
private cache = new Map<string, { value: string | null; at: number }>();
|
||||
|
||||
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
const hit = this.cache.get(key);
|
||||
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
||||
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
|
||||
let value = row?.value ?? null;
|
||||
if (value !== null && SECRET_SETTINGS.has(key)) {
|
||||
try {
|
||||
value = this.ctx.secrets.decrypt(value);
|
||||
} catch {
|
||||
value = null;
|
||||
}
|
||||
}
|
||||
this.cache.set(key, { value, at: Date.now() });
|
||||
return value;
|
||||
}
|
||||
|
||||
async bool(key: string, fallback: boolean): Promise<boolean> {
|
||||
const v = await this.get(key);
|
||||
return v === null || v === '' ? fallback : v === 'true';
|
||||
}
|
||||
|
||||
async json<T>(key: string, fallback: T): Promise<T> {
|
||||
const v = await this.get(key);
|
||||
if (!v) return fallback;
|
||||
try {
|
||||
return JSON.parse(v) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
|
||||
else {
|
||||
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
|
||||
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
|
||||
}
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
async setMany(values: Record<string, string | null>): Promise<void> {
|
||||
for (const [k, v] of Object.entries(values)) await this.set(k, v);
|
||||
}
|
||||
|
||||
forget(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
|
||||
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
|
||||
* however the process was started (PM2 doesn't set npm_package_version).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
let cached: string | null = null;
|
||||
|
||||
export function appVersion(): string {
|
||||
if (!cached) {
|
||||
try {
|
||||
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
||||
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
|
||||
} catch {
|
||||
cached = '0.0.0';
|
||||
}
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4 and Accounts). The Website links
|
||||
* to the church's **Accounts** (signing in: the link's secret is where the client secret comes
|
||||
* from, and Accounts registers this site as an OIDC client when it accepts) and, for the event
|
||||
* feed, to **Events** and later the **App**.
|
||||
*
|
||||
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in this
|
||||
* site's cached `linkedProducts` (same church), signed with the key the Hub listed for it.
|
||||
*/
|
||||
import {
|
||||
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
|
||||
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
|
||||
} from '@crosscode/contracts';
|
||||
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { callSibling, LinkCallError, siblingUrl } from './http.js';
|
||||
import { keyPair, linkedProducts, listedProduct } from './store.js';
|
||||
|
||||
export class LinkError extends Error {
|
||||
constructor(message: string, public code: string, public status = 400) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The products the Website links to. */
|
||||
const LINKABLE = new Set(['accounts', 'events', 'app']);
|
||||
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||
|
||||
type Actor = { id: string | null; role: string };
|
||||
|
||||
async function self(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
if (!installId) throw new LinkError('The Website isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
|
||||
const { privateKeyPem } = await keyPair(ctx);
|
||||
return { installId, url: ctx.config.publicUrl, privateKeyPem };
|
||||
}
|
||||
|
||||
const party = (s: { installId: string; url: string }) => ({ product: 'website' as const, installId: s.installId, url: s.url });
|
||||
|
||||
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
|
||||
const now = ctx.now();
|
||||
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||
try {
|
||||
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if ((e as { code?: string }).code === 'P2002') return false;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
|
||||
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById, lastSyncError: null };
|
||||
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||
}
|
||||
|
||||
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: Actor | null, req: Request | undefined, by: string) =>
|
||||
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
|
||||
|
||||
/** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */
|
||||
export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const sibling = await listedProduct(ctx, installId);
|
||||
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||
const me = await self(ctx);
|
||||
const secret = newLinkSecret();
|
||||
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
let reply: unknown;
|
||||
try {
|
||||
reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
|
||||
} catch (e) {
|
||||
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
|
||||
throw e;
|
||||
}
|
||||
const parsed = linkConnectedSchema.safeParse(reply);
|
||||
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
|
||||
const r: LinkConnected = parsed.data;
|
||||
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() }).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
|
||||
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
|
||||
}
|
||||
const link = await saveLink(ctx, sibling, secret, actor.id);
|
||||
await logLink(ctx, 'product_link_connected', link, actor, req, 'website');
|
||||
return link;
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/connect` (a sibling's admin pressed Connect there). */
|
||||
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise<LinkConnected> {
|
||||
const parsed = linkConnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const sibling = await listedProduct(ctx, m.from.installId);
|
||||
if (!sibling || sibling.product !== m.from.product || !LINKABLE.has(sibling.product)) {
|
||||
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
|
||||
}
|
||||
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
|
||||
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
const link = await saveLink(ctx, sibling, m.secret, null);
|
||||
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
|
||||
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
}
|
||||
|
||||
/** This site ends a link. The local link goes even if the sibling can't be reached. */
|
||||
export async function disconnectFrom(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId } });
|
||||
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||
let told = false;
|
||||
let problem: string | null = null;
|
||||
try {
|
||||
const me = await self(ctx);
|
||||
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
|
||||
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||
told = true;
|
||||
} catch (e) {
|
||||
problem = (e as Error).message;
|
||||
}
|
||||
await ctx.db.productLink.delete({ where: { installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'website');
|
||||
return { told, problem };
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
|
||||
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise<void> {
|
||||
const parsed = linkDisconnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||
if (!link) return;
|
||||
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
await ctx.db.productLink.delete({ where: { installId: link.installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Website signs in through Accounts, so it connects to the church's Accounts by itself once the
|
||||
* Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat.
|
||||
* Never throws: a failure is tried again at the next heartbeat.
|
||||
*/
|
||||
export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
|
||||
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped';
|
||||
const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts');
|
||||
if (!listed) return 'skipped';
|
||||
try {
|
||||
await connectTo(ctx, listed.installId, { id: null, role: 'system' });
|
||||
return 'connected';
|
||||
} catch (e) {
|
||||
console.warn('[links] Connecting to Accounts failed:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
|
||||
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
|
||||
*/
|
||||
import dns from 'node:dns/promises';
|
||||
import net from 'node:net';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
const TIMEOUT_MS = 15000;
|
||||
const MAX_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export class LinkCallError extends Error {
|
||||
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function isPrivateAddress(ip: string): boolean {
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number) as [number, number];
|
||||
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
const v = ip.toLowerCase();
|
||||
if (v === '::1' || v === '::') return true;
|
||||
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
|
||||
if (mapped) return isPrivateAddress(mapped[1]!);
|
||||
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise<URL> {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
|
||||
} catch {
|
||||
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
|
||||
}
|
||||
const allow = ctx.config.allowPrivateLinks;
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||
if (!allow) {
|
||||
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
|
||||
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: init.method,
|
||||
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
|
||||
body: init.body,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE');
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||
const text = await res.text();
|
||||
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
|
||||
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* The link endpoints siblings call (`crosscode.link/1`): Accounts (or Events) connecting to and
|
||||
* disconnecting from this site. Errors use the link protocol's `{ code, message }`.
|
||||
*/
|
||||
import express from 'express';
|
||||
import { LINK_PATHS } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
|
||||
|
||||
export function linksRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
const json = express.json({ limit: '32kb' });
|
||||
const fail = (res: express.Response, e: unknown) => {
|
||||
if (e instanceof LinkError) return res.status(e.status).json({ code: e.code, message: e.message });
|
||||
console.error('[links]', e);
|
||||
return res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong.' });
|
||||
};
|
||||
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
res.json(await acceptConnect(ctx, req.body, req));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
r.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
await acceptDisconnect(ctx, req.body, req);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
|
||||
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
|
||||
* hub_linked_products.
|
||||
*/
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
type LinkedProduct = hub.LinkedProduct;
|
||||
|
||||
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
|
||||
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
|
||||
const pair = generateEd25519();
|
||||
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
|
||||
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||
}
|
||||
|
||||
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
|
||||
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
|
||||
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
|
||||
}
|
||||
|
||||
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
|
||||
if (!Array.isArray(list)) return;
|
||||
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
|
||||
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
|
||||
}
|
||||
|
||||
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
|
||||
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* What the public site shows right now: Coming soon until the first publish (§5, decision 3), then
|
||||
* the latest published version. After the first publish there's no going back to Coming soon.
|
||||
*/
|
||||
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export type SiteStatus =
|
||||
| { mode: 'coming-soon' }
|
||||
| { mode: 'published'; version: number; publishedAt: string; template: WebsiteTemplate | null };
|
||||
|
||||
export async function siteStatus(ctx: Ctx): Promise<SiteStatus> {
|
||||
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true, publishedAt: true, snapshot: true } });
|
||||
if (!latest) return { mode: 'coming-soon' };
|
||||
const t = (latest.snapshot as { design?: { template?: unknown } } | null)?.design?.template;
|
||||
const template = (WEBSITE_TEMPLATES as readonly unknown[]).includes(t) ? (t as WebsiteTemplate) : null;
|
||||
return { mode: 'published', version: latest.number, publishedAt: latest.publishedAt.toISOString(), template };
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Section variants per template (docs/WEBSITE-1.0-PLAN.md §3, "Section variants per template",
|
||||
* decision 16, confirmed 2026-11-25).
|
||||
*
|
||||
* Every template draws every variant, so nothing is ever unavailable and a template switch never
|
||||
* needs a fallback. A template only sets which variant each section starts with, which ones it
|
||||
* recommends, its header options, its homepage order and its style defaults.
|
||||
*
|
||||
* The ids are stored on each section (`hero.variant = "photo"`), so **an id never changes or goes
|
||||
* away** once released, like the font pairing ids in `@crosscode/contracts`.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { Corners, WebsiteTemplate } from '@crosscode/contracts';
|
||||
|
||||
/** The homepage section types and their variant ids. */
|
||||
export const SECTION_VARIANTS = {
|
||||
hero: ['photo', 'video', 'collage', 'split', 'text'],
|
||||
serviceTimes: ['panel', 'strip', 'map'],
|
||||
welcome: ['text', 'image-text', 'pastor'],
|
||||
ministries: ['cards', 'list', 'bands'],
|
||||
team: ['faces', 'list', 'featured'],
|
||||
events: ['cards', 'list', 'calendar'],
|
||||
latestMessage: ['video', 'card', 'compact'],
|
||||
invitation: ['banner', 'centred', 'image'],
|
||||
} as const;
|
||||
|
||||
export type SectionType = keyof typeof SECTION_VARIANTS;
|
||||
export type Variant<S extends SectionType = SectionType> = (typeof SECTION_VARIANTS)[S][number];
|
||||
export const SECTION_TYPES = Object.keys(SECTION_VARIANTS) as [SectionType, ...SectionType[]];
|
||||
export const sectionTypeSchema = z.enum(SECTION_TYPES);
|
||||
|
||||
/** Whether `variant` is one of `section`'s ids. */
|
||||
export function isVariant<S extends SectionType>(section: S, variant: string): variant is Variant<S> {
|
||||
return (SECTION_VARIANTS[section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** Per section: the default first, then the other recommended variants. */
|
||||
type Recommendations = { [S in SectionType]: readonly [Variant<S>, ...Variant<S>[]] };
|
||||
|
||||
export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
heritage: {
|
||||
hero: ['photo', 'split', 'text'],
|
||||
serviceTimes: ['panel', 'map'],
|
||||
welcome: ['pastor', 'text'],
|
||||
ministries: ['list', 'cards'],
|
||||
team: ['featured', 'faces'],
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['centred', 'banner'],
|
||||
},
|
||||
bold: {
|
||||
hero: ['video', 'photo', 'split'],
|
||||
serviceTimes: ['strip', 'map'],
|
||||
welcome: ['image-text', 'pastor'],
|
||||
ministries: ['bands', 'cards'],
|
||||
team: ['faces', 'featured'],
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['video', 'card'],
|
||||
invitation: ['image', 'banner'],
|
||||
},
|
||||
community: {
|
||||
hero: ['collage', 'photo', 'split'],
|
||||
serviceTimes: ['map', 'panel'],
|
||||
welcome: ['pastor', 'image-text'],
|
||||
ministries: ['cards', 'bands'],
|
||||
team: ['faces', 'featured'],
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['banner', 'image'],
|
||||
},
|
||||
clean: {
|
||||
hero: ['text', 'split', 'photo'],
|
||||
serviceTimes: ['strip', 'panel'],
|
||||
welcome: ['text', 'image-text'],
|
||||
ministries: ['list', 'cards'],
|
||||
team: ['list', 'faces'],
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['compact', 'card'],
|
||||
invitation: ['centred', 'banner'],
|
||||
},
|
||||
};
|
||||
|
||||
export function defaultVariant<S extends SectionType>(template: WebsiteTemplate, section: S): Variant<S> {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly Variant<S>[])[0]!;
|
||||
}
|
||||
|
||||
export function isRecommended(template: WebsiteTemplate, section: SectionType, variant: string): boolean {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** The "Header" style setting: each template's options, default first. */
|
||||
export const TEMPLATE_HEADERS = {
|
||||
heritage: ['centred', 'centred-top-bar'],
|
||||
bold: ['transparent', 'solid'],
|
||||
community: ['logo-left-button', 'logo-left-tinted'],
|
||||
clean: ['small', 'small-menu'],
|
||||
} as const satisfies Record<WebsiteTemplate, readonly [string, ...string[]]>;
|
||||
|
||||
/**
|
||||
* The transparent header only sits over a photo, video or collage hero; on any other first section
|
||||
* it's drawn solid, so it never puts white text on white.
|
||||
*/
|
||||
export function headerIsTransparent(template: WebsiteTemplate, header: string, heroVariant: Variant<'hero'> | null): boolean {
|
||||
return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant);
|
||||
}
|
||||
|
||||
/** A homepage entry: the section and whether it shows. */
|
||||
export type HomeEntry = { section: SectionType; hidden: boolean };
|
||||
|
||||
const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [
|
||||
...shown.map((section) => ({ section, hidden: false })),
|
||||
...hidden.map((section) => ({ section, hidden: true })),
|
||||
];
|
||||
|
||||
/** The default homepage order (the church can reorder, hide and show). Every section is listed once. */
|
||||
export const TEMPLATE_HOME_ORDER: Record<WebsiteTemplate, HomeEntry[]> = {
|
||||
heritage: order(['hero', 'serviceTimes', 'welcome', 'latestMessage', 'ministries', 'team', 'events', 'invitation']),
|
||||
bold: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'ministries', 'invitation'], ['team']),
|
||||
community: order(['hero', 'welcome', 'serviceTimes', 'ministries', 'team', 'events', 'latestMessage', 'invitation']),
|
||||
clean: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'invitation'], ['ministries', 'team']),
|
||||
};
|
||||
|
||||
/** The Website-only style settings (§3, "Style settings"). Fonts and corners are the church's, shared. */
|
||||
export const SECTION_COLOURS = ['light', 'tinted', 'mixed'] as const;
|
||||
export const SPACINGS = ['airy', 'compact'] as const;
|
||||
export const BUTTONS = ['solid', 'outline', 'pill'] as const;
|
||||
export const IMAGE_TREATMENTS = ['natural', 'mono', 'duotone'] as const;
|
||||
|
||||
export type SiteStyle = {
|
||||
sectionColour: (typeof SECTION_COLOURS)[number];
|
||||
spacing: (typeof SPACINGS)[number];
|
||||
buttons: (typeof BUTTONS)[number];
|
||||
images: (typeof IMAGE_TREATMENTS)[number];
|
||||
header: string;
|
||||
};
|
||||
|
||||
export const TEMPLATE_STYLE: Record<WebsiteTemplate, SiteStyle & { suggestedCorners: Corners }> = {
|
||||
heritage: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'centred', suggestedCorners: 'sharp' },
|
||||
bold: { sectionColour: 'mixed', spacing: 'compact', buttons: 'solid', images: 'natural', header: 'transparent', suggestedCorners: 'sharp' },
|
||||
community: { sectionColour: 'tinted', spacing: 'airy', buttons: 'pill', images: 'natural', header: 'logo-left-button', suggestedCorners: 'round' },
|
||||
clean: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'small', suggestedCorners: 'soft' },
|
||||
};
|
||||
|
||||
const STYLE_KEYS = ['sectionColour', 'spacing', 'buttons', 'images', 'header'] as const;
|
||||
|
||||
/** The site's design: what a template switch changes. Content is never part of it. */
|
||||
export type SiteDesign = {
|
||||
template: WebsiteTemplate;
|
||||
variants: { [S in SectionType]: Variant<S> };
|
||||
home: HomeEntry[];
|
||||
style: SiteStyle;
|
||||
};
|
||||
|
||||
/** A fresh site on `template`: every default. */
|
||||
export function defaultDesign(template: WebsiteTemplate): SiteDesign {
|
||||
const variants = Object.fromEntries(SECTION_TYPES.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
|
||||
const { suggestedCorners: _c, ...style } = TEMPLATE_STYLE[template];
|
||||
return { template, variants, home: TEMPLATE_HOME_ORDER[template].map((e) => ({ ...e })), style };
|
||||
}
|
||||
|
||||
export type DesignChange = { what: string; from: string; to: string };
|
||||
|
||||
const sameOrder = (a: HomeEntry[], b: HomeEntry[]) =>
|
||||
a.length === b.length && a.every((e, i) => e.section === b[i]!.section && e.hidden === b[i]!.hidden);
|
||||
|
||||
/**
|
||||
* Switching template (§3, "Switching template"): anything still on the old template's default
|
||||
* moves to the new template's default; anything the church chose stays. Returns the new design and
|
||||
* what moved, for the Publish screen ("Hero: Collage → Text only, Clean's default").
|
||||
*/
|
||||
export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { design: SiteDesign; changes: DesignChange[] } {
|
||||
if (current.template === to) return { design: current, changes: [] };
|
||||
const from = current.template;
|
||||
const target = defaultDesign(to);
|
||||
const changes: DesignChange[] = [{ what: 'template', from, to }];
|
||||
|
||||
const variants = { ...current.variants } as Record<SectionType, string>;
|
||||
for (const s of SECTION_TYPES) {
|
||||
const next = target.variants[s];
|
||||
if (current.variants[s] === defaultVariant(from, s) && next !== current.variants[s]) {
|
||||
changes.push({ what: `${s}.variant`, from: current.variants[s], to: next });
|
||||
variants[s] = next;
|
||||
}
|
||||
}
|
||||
|
||||
const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]);
|
||||
const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e }));
|
||||
if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` });
|
||||
|
||||
const style = { ...current.style };
|
||||
const oldStyle = TEMPLATE_STYLE[from];
|
||||
for (const k of STYLE_KEYS) {
|
||||
// A header from the old template's options means nothing in the new one, so it always moves.
|
||||
const untouched = current.style[k] === oldStyle[k] || (k === 'header' && !(TEMPLATE_HEADERS[to] as readonly string[]).includes(current.style.header));
|
||||
if (untouched && current.style[k] !== target.style[k]) {
|
||||
changes.push({ what: `style.${k}`, from: current.style[k], to: target.style[k] });
|
||||
(style as Record<string, string>)[k] = target.style[k];
|
||||
}
|
||||
}
|
||||
|
||||
return { design: { template: to, variants: variants as SiteDesign['variants'], home, style }, changes };
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { createCtx, type Db } from '../src/context.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
import { appVersion } from '../src/lib/version.js';
|
||||
|
||||
type Version = { number: number; publishedAt: Date; snapshot: unknown };
|
||||
|
||||
/** Just what the app uses so far: a ping and the latest published version. */
|
||||
function fakeDb(opts: { up?: boolean; versions?: Version[] } = {}): Db {
|
||||
const versions = opts.versions ?? [];
|
||||
return {
|
||||
$queryRaw: async () => {
|
||||
if (opts.up === false) throw new Error('down');
|
||||
return [{ '?column?': 1 }];
|
||||
},
|
||||
siteVersion: {
|
||||
findFirst: async () => [...versions].sort((a, b) => b.number - a.number)[0] ?? null,
|
||||
},
|
||||
} as unknown as Db;
|
||||
}
|
||||
|
||||
const app = (db: Db) => createApp(createCtx(loadConfig({}), db));
|
||||
|
||||
describe('the app', () => {
|
||||
it('answers /api/health with the product and version', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/health');
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body, { status: 'ok', product: 'website', version: appVersion(), db: true });
|
||||
});
|
||||
|
||||
it('says 503 when the database is down', async () => {
|
||||
const res = await request(app(fakeDb({ up: false }))).get('/api/health');
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal(res.body.db, false);
|
||||
});
|
||||
|
||||
it('shows Coming soon until the first publish', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/v1/site/status');
|
||||
assert.deepEqual(res.body, { mode: 'coming-soon' });
|
||||
});
|
||||
|
||||
it('shows the latest published version after it', async () => {
|
||||
const at = new Date('2026-12-01T08:00:00Z');
|
||||
const res = await request(app(fakeDb({ versions: [
|
||||
{ number: 1, publishedAt: new Date('2026-11-30T08:00:00Z'), snapshot: { design: { template: 'heritage' } } },
|
||||
{ number: 2, publishedAt: at, snapshot: { design: { template: 'clean' } } },
|
||||
] }))).get('/api/v1/site/status');
|
||||
assert.deepEqual(res.body, { mode: 'published', version: 2, publishedAt: at.toISOString(), template: 'clean' });
|
||||
});
|
||||
|
||||
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/nothing');
|
||||
assert.equal(res.status, 404);
|
||||
assert.equal(res.body.error.code, 'NOT_FOUND');
|
||||
assert.equal(res.headers['x-robots-tag'], 'noindex');
|
||||
assert.equal(res.headers['x-powered-by'], undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('config', () => {
|
||||
it('refuses production without a secret', () => {
|
||||
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /WEBSITE_SECRET/);
|
||||
});
|
||||
|
||||
it('defaults to the development ports', () => {
|
||||
const c = loadConfig({});
|
||||
assert.equal(c.port, 5300);
|
||||
assert.equal(c.publicUrl, 'http://localhost:3300');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { after, describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { churchExportSchema, hub, INTERNAL_ID_KEYS, LINK_SCHEMA, linkConnectSchema, type LinkConnected } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import { buildExport } from '../src/export/churchExport.js';
|
||||
import { stats } from '../src/hub/client.js';
|
||||
import { connectAccountsIfListed } from '../src/links/connect.js';
|
||||
import { keyPair, saveLinkedProducts } from '../src/links/store.js';
|
||||
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID } from './support/harness.js';
|
||||
|
||||
const accountsKeys = generateEd25519();
|
||||
const accountsPublic = ed25519PublicToPem(accountsKeys.publicKey);
|
||||
|
||||
/** The church's Accounts, accepting a connect as apps/accounts/backend/src/links/connect.ts does. */
|
||||
async function fakeAccounts(websitePublicKey: () => Promise<string>, opts: { badSignature?: boolean } = {}) {
|
||||
const app = express();
|
||||
const seen: unknown[] = [];
|
||||
app.post('/api/links/v1/connect', express.json(), async (req, res) => {
|
||||
const m = linkConnectSchema.parse(req.body);
|
||||
seen.push(m);
|
||||
if (!verifyLink(m as unknown as Record<string, unknown>, await websitePublicKey()).ok) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
|
||||
const reply = signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connected', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: `http://127.0.0.1:${port}` },
|
||||
to: { installId: m.from.installId }, inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
|
||||
}, opts.badSignature ? generateEd25519().privateKeyPem : accountsKeys.privateKeyPem);
|
||||
return res.json(reply);
|
||||
});
|
||||
const server = http.createServer(app);
|
||||
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
return { url: `http://127.0.0.1:${port}`, seen, close: () => new Promise((r) => server.close(r)) };
|
||||
}
|
||||
|
||||
const closers: (() => Promise<unknown>)[] = [];
|
||||
after(async () => { for (const c of closers) await c(); });
|
||||
|
||||
describe('linking to the church\'s Accounts', () => {
|
||||
it('connects by itself once the Hub lists an Accounts, with a secret both sides keep', async () => {
|
||||
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
|
||||
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
|
||||
closers.push(accounts.close);
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'nothing listed yet');
|
||||
|
||||
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'connected');
|
||||
const link = await h.db.productLink.findUnique({ where: { installId: ACCOUNTS_INSTALL_ID } });
|
||||
assert.equal(link!.product, 'accounts');
|
||||
const sent = accounts.seen[0] as { secret: string; from: { product: string; installId: string } };
|
||||
assert.equal(sent.from.product, 'website');
|
||||
assert.equal(sent.from.installId, INSTALL_ID);
|
||||
assert.equal(h.ctx.secrets.decrypt(String(link!.secret)), sent.secret);
|
||||
assert.notEqual(link!.secret, sent.secret, 'stored encrypted');
|
||||
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'already linked');
|
||||
assert.equal(accounts.seen.length, 1);
|
||||
});
|
||||
|
||||
it('doesn\'t keep a link whose answer isn\'t signed with the key the Hub listed', async () => {
|
||||
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
|
||||
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem, { badSignature: true });
|
||||
closers.push(accounts.close);
|
||||
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'failed');
|
||||
assert.equal(await h.db.productLink.count(), 0);
|
||||
});
|
||||
|
||||
it('accepts a connect from a listed sibling signed with its key, once', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test', publicKey: accountsPublic }]);
|
||||
const message = () => signLink({
|
||||
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test' },
|
||||
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
|
||||
}, accountsKeys.privateKeyPem);
|
||||
const m = message();
|
||||
const res = await request(h.app).post('/api/links/v1/connect').send(m);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.type, 'link.connected');
|
||||
assert.ok(verifyLink(res.body, (await keyPair(h.ctx)).publicKeyPem).ok);
|
||||
assert.equal(await h.db.productLink.count(), 1);
|
||||
|
||||
assert.equal((await request(h.app).post('/api/links/v1/connect').send(m)).body.code, 'REPLAYED');
|
||||
const forged = { ...message(), signature: message().signature };
|
||||
assert.equal((await request(h.app).post('/api/links/v1/connect').send(forged)).status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the heartbeat and the export', () => {
|
||||
it('reports aggregate counts the Hub accepts', async () => {
|
||||
const h = await harness();
|
||||
await h.db.mediaAsset.create({ data: { filename: 'hero.jpg', mime: 'image/jpeg', bytes: 1200 } });
|
||||
await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
const s = await stats(h.ctx);
|
||||
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
|
||||
assert.equal(s.storage.usedBytes, 1200);
|
||||
assert.deepEqual(s.pages, { published: 0, drafts: 1 });
|
||||
});
|
||||
|
||||
it('exports the content in crosscode.church-export/1, without internal ids', async () => {
|
||||
const h = await harness();
|
||||
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: {}, home: [], style: { spacing: 'airy' } } });
|
||||
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'hero', variant: 'text', data: { headline: 'Welcome home' } } });
|
||||
const img = await h.db.mediaAsset.create({ data: { filename: '2026/hero.jpg', mime: 'image/jpeg', bytes: 1200, alt: 'The hall' } });
|
||||
await h.db.simpleEvent.create({ data: { slug: 'picnic', title: 'Picnic', startsAt: new Date('2026-12-05T08:00:00Z'), imageId: img.id, publishedAt: new Date() } });
|
||||
await h.db.message.create({ data: { slug: 'hope', title: 'Hope', date: new Date('2026-11-22T08:00:00Z'), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abc' } });
|
||||
await h.db.websiteUser.create({ data: { id: '11111111-1111-4111-8111-111111111111', name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
|
||||
await h.db.siteVersion.create({ data: { number: 1, snapshot: {}, publishedBy: '11111111-1111-4111-8111-111111111111', note: 'First' } });
|
||||
|
||||
const data = await buildExport(h.ctx);
|
||||
assert.ok(churchExportSchema.safeParse(data).success);
|
||||
const w = data.website!;
|
||||
assert.equal(w.template, 'clean');
|
||||
assert.equal(w.pages[0]!.path, '/');
|
||||
assert.deepEqual(w.pages[0]!.sections[0], { type: 'hero', variant: 'text', hidden: false, content: { headline: 'Welcome home' } });
|
||||
assert.equal(w.events[0]!.image, 'uploads/2026/hero.jpg');
|
||||
assert.equal(w.messages[0]!.source, 'youtube-feed');
|
||||
assert.deepEqual(w.versions[0], { number: 1, publishedAt: w.versions[0]!.publishedAt, by: 'Sam', note: 'First' });
|
||||
assert.equal(data.people[0]!.role, 'website owner');
|
||||
|
||||
const keys: string[] = [];
|
||||
const walk = (x: unknown) => {
|
||||
if (Array.isArray(x)) x.forEach(walk);
|
||||
else if (x && typeof x === 'object') for (const [k, v] of Object.entries(x)) { keys.push(k); walk(v); }
|
||||
};
|
||||
walk({ ...data, website: { ...w, pages: w.pages.map((p) => ({ ...p, sections: p.sections.map((s) => ({ ...s, content: {} })) })) } });
|
||||
assert.deepEqual(keys.filter((k) => INTERNAL_ID_KEYS.test(k)), []);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { cookieHeader, cookiesFrom, harness, SITE } from './support/harness.js';
|
||||
|
||||
const OWNER = '11111111-1111-4111-8111-111111111111';
|
||||
const OTHER = '22222222-2222-4222-8222-222222222222';
|
||||
|
||||
/** Signs in from `returnTo` through the stand-in Accounts; returns the callback's response and the cookies after it. */
|
||||
async function signIn(h: Awaited<ReturnType<typeof harness>>, returnTo = '/admin/pages?x=1', cookies: Record<string, string> = {}, mfa = false) {
|
||||
const start = await request(h.app).get(`/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? '&mfa=1' : ''}`).set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(start.status, 303);
|
||||
const after = cookiesFrom(start, cookies);
|
||||
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
|
||||
return { start, back, cookies: cookiesFrom(back, after) };
|
||||
}
|
||||
|
||||
describe('signing in to the admin through Accounts', () => {
|
||||
it('sends people to Accounts with the page they were on', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin%2Fpages');
|
||||
assert.equal(res.status, 303);
|
||||
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//);
|
||||
assert.deepEqual(h.fake.started, [{ returnTo: '/admin/pages', requireTwoFactor: false }]);
|
||||
assert.match(String(res.headers['set-cookie']), /ccw_signin=.*Path=\/api\/auth.*HttpOnly/);
|
||||
});
|
||||
|
||||
it('refuses a foreign return address (back to the home page instead)', async () => {
|
||||
const h = await harness();
|
||||
await request(h.app).get('/api/auth/signin?returnTo=https%3A%2F%2Fevil.test%2F');
|
||||
assert.equal(h.fake.started[0]!.returnTo, '/');
|
||||
});
|
||||
|
||||
it('says so when the Website isn\'t linked to Accounts yet', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
|
||||
assert.equal(res.status, 303);
|
||||
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_UNAVAILABLE&returnTo=%2Fadmin`);
|
||||
});
|
||||
|
||||
it('makes the Hub\'s admin email (verified) the first Owner and lands on the page they started from', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, email: 'Pastor@Hope.test' };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.equal(back.headers.location, `${SITE}/admin/pages?x=1`);
|
||||
assert.ok(cookies.ccw_session);
|
||||
assert.match(String(back.headers['set-cookie']), /ccw_session=.*HttpOnly/);
|
||||
|
||||
const me = await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(me.status, 200);
|
||||
assert.equal(me.body.user.role, 'owner');
|
||||
assert.equal(me.body.user.email, 'pastor@hope.test');
|
||||
assert.equal(me.body.mfa, true);
|
||||
const audit = await h.db.auditLog.findMany({ where: { action: 'first_owner_signed_in' } });
|
||||
assert.equal(audit.length, 1);
|
||||
});
|
||||
|
||||
it('never makes a second Owner, nor one from an unverified email', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, email_verified: false };
|
||||
assert.match((await signIn(h)).back.headers.location!, /code=NO_ACCESS/);
|
||||
assert.equal(await h.db.websiteUser.count(), 0);
|
||||
|
||||
h.fake.next = { sub: OWNER };
|
||||
await signIn(h);
|
||||
h.fake.next = { sub: OTHER };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.match(back.headers.location!, /code=NO_ACCESS/);
|
||||
assert.equal(cookies.ccw_session, undefined);
|
||||
assert.equal(await h.db.websiteUser.count(), 1);
|
||||
});
|
||||
|
||||
it('gives someone without a role on the Website no session', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OTHER, email: 'member@hope.test' };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.match(back.headers.location!, /\/auth\/problem\?code=NO_ACCESS/);
|
||||
assert.equal(cookies.ccw_session, undefined);
|
||||
});
|
||||
|
||||
it('asks Accounts again with a second step for an Owner who signed in without one, once', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd'] };
|
||||
const first = await signIn(h, '/admin');
|
||||
assert.equal(first.back.headers.location, `${SITE}/api/auth/signin?mfa=1&returnTo=%2Fadmin`);
|
||||
assert.equal(first.cookies.ccw_session, undefined);
|
||||
|
||||
// Accounts still says no second step: explained, not looped.
|
||||
const second = await signIn(h, '/admin', first.cookies, true);
|
||||
assert.equal(h.fake.started.at(-1)!.requireTwoFactor, true);
|
||||
assert.match(second.back.headers.location!, /code=TWO_FACTOR_NEEDED/);
|
||||
|
||||
// With it: signed in.
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd', 'mfa'] };
|
||||
const third = await signIn(h, '/admin', {}, true);
|
||||
assert.ok(third.cookies.ccw_session);
|
||||
});
|
||||
|
||||
it('lets an Editor in without a second step, and Owners too when the church turned the rule off', async () => {
|
||||
const h = await harness();
|
||||
await h.db.websiteUser.create({ data: { id: OTHER, name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
|
||||
h.fake.next = { sub: OTHER, email: 'ed@hope.test', amr: ['pwd'] };
|
||||
assert.ok((await signIn(h)).cookies.ccw_session);
|
||||
|
||||
await h.ctx.settings.set('two_factor_required_for_admins', 'false');
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd'] };
|
||||
assert.ok((await signIn(h)).cookies.ccw_session);
|
||||
});
|
||||
|
||||
it('keeps the admin API to signed-in people', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).get('/api/v1/admin/me');
|
||||
assert.equal(res.status, 401);
|
||||
assert.equal(res.body.error.code, 'SIGNED_OUT');
|
||||
const me = await request(h.app).get('/api/auth/me').set('Cookie', 'ccw_session=made-up');
|
||||
assert.equal(me.status, 401);
|
||||
});
|
||||
|
||||
it('signs out here, then at Accounts (all the church\'s sites)', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER };
|
||||
const { cookies } = await signIn(h);
|
||||
const out = await request(h.app).post('/api/auth/signout').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(out.status, 303);
|
||||
assert.equal(out.headers.location, `https://accounts.hope.test/api/oidc/session/end?id_token_hint=id-token-for-${OWNER}`);
|
||||
assert.equal(await h.db.session.count(), 0);
|
||||
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
|
||||
});
|
||||
|
||||
it('ends the person\'s sessions when Accounts says they signed out somewhere', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER };
|
||||
const { cookies } = await signIn(h);
|
||||
const res = await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: JSON.stringify({ sub: OWNER, sid: 'abc' }) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
|
||||
assert.equal((await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: 'nonsense' })).status, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Accounts' calls", () => {
|
||||
const call = (type: string, extra: object) => JSON.stringify({ schema: 'crosscode.identity/1', callId: '33333333-3333-4333-8333-333333333333', occurredAt: new Date().toISOString(), sub: OWNER, type, ...extra });
|
||||
|
||||
it('refuses a call Accounts didn\'t sign', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').send(call('user.updated', {}));
|
||||
assert.equal(res.status, 401);
|
||||
});
|
||||
|
||||
it('keeps the admin\'s name and email current, exports them, and removes them when the account goes', async () => {
|
||||
const h = await harness();
|
||||
await h.db.websiteUser.create({ data: { id: OWNER, name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
|
||||
await h.db.session.create({ data: { tokenHash: 'x', userId: OWNER, expiresAt: new Date(Date.now() + 1e9) } });
|
||||
const send = (body: string) => request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').set('x-test-signed', 'yes').send(body);
|
||||
|
||||
const profile = { name: 'Pastor Samuel', email: 'Sam@Hope.test', email_verified: true, phone_number: null, news_consent: { email: false, whatsapp: false } };
|
||||
assert.deepEqual((await send(call('user.updated', { profile }))).body, { schema: 'crosscode.identity/1', ok: true });
|
||||
const u = await h.db.websiteUser.findUnique({ where: { id: OWNER } });
|
||||
assert.equal(u!.name, 'Pastor Samuel');
|
||||
assert.equal(u!.email, 'sam@hope.test');
|
||||
|
||||
const exp = await send(call('user.export', { exportId: '44444444-4444-4444-8444-444444444444' }));
|
||||
assert.equal(exp.body.product, 'website');
|
||||
assert.equal(exp.body.sections[0].records[0].role, 'owner');
|
||||
|
||||
const del = await send(call('user.deleted', {}));
|
||||
assert.equal(del.body.status, 'deleted');
|
||||
assert.equal(await h.db.websiteUser.count(), 0);
|
||||
assert.equal(await h.db.session.count(), 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* The Website's app on an in-memory database, with a stand-in for `@crosscode/auth-client` (the
|
||||
* real one is tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts),
|
||||
* linked to a church's Accounts and registered with the Hub.
|
||||
*/
|
||||
import type { IdentityClaims } from '@crosscode/contracts';
|
||||
import type { AuthClientModule } from '../../src/auth/accounts.js';
|
||||
import { createApp } from '../../src/app.js';
|
||||
import { createCtx, type Ctx, type Db } from '../../src/context.js';
|
||||
import { loadConfig } from '../../src/lib/config.js';
|
||||
import { memoryDb, type MemoryDb } from './memoryDb.js';
|
||||
|
||||
export const SITE = 'https://www.hope.test';
|
||||
export const ACCOUNTS = 'https://accounts.hope.test';
|
||||
export const ADMIN_EMAIL = 'pastor@hope.test';
|
||||
export const INSTALL_ID = '6f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f';
|
||||
export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||
|
||||
/** What the stand-in Accounts answers with at the next callback. */
|
||||
export type FakeAccounts = {
|
||||
next: Partial<IdentityClaims> & { sub: string };
|
||||
started: { returnTo: string; requireTwoFactor: boolean }[];
|
||||
};
|
||||
|
||||
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
|
||||
return {
|
||||
schema: 'crosscode.identity/1',
|
||||
name: 'Pastor Sam',
|
||||
email: ADMIN_EMAIL,
|
||||
email_verified: true,
|
||||
phone_number: null,
|
||||
news_consent: { email: false, whatsapp: false },
|
||||
amr: ['pwd', 'mfa'],
|
||||
two_factor: 'totp',
|
||||
privacy_notice_version: 1,
|
||||
...over,
|
||||
} as IdentityClaims;
|
||||
}
|
||||
|
||||
function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
|
||||
class SignInError extends Error {
|
||||
constructor(message: string, public code: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
return {
|
||||
SignInError,
|
||||
accountsClient: async () => ({
|
||||
startSignIn: async (returnTo: string, opts: { requireTwoFactor?: boolean } = {}) => {
|
||||
fake.started.push({ returnTo, requireTwoFactor: !!opts.requireTwoFactor });
|
||||
return { url: `${ACCOUNTS}/api/oidc/auth?mfa=${opts.requireTwoFactor ? 1 : 0}`, cookie: Buffer.from(JSON.stringify({ returnTo })).toString('base64url') };
|
||||
},
|
||||
finishSignIn: async (_url: URL, cookie: string | undefined) => {
|
||||
if (!cookie) throw new SignInError('expired', 'NO_PENDING');
|
||||
const { returnTo } = JSON.parse(Buffer.from(cookie, 'base64url').toString()) as { returnTo: string };
|
||||
return { claims: claims(fake.next), returnTo, idToken: `id-token-for-${fake.next.sub}` };
|
||||
},
|
||||
signOutUrl: (idToken?: string) => `${ACCOUNTS}/api/oidc/session/end?id_token_hint=${idToken ?? ''}`,
|
||||
verifyLogoutToken: async (token: string) => {
|
||||
try {
|
||||
return JSON.parse(token) as { sub: string; sid: string | null };
|
||||
} catch {
|
||||
throw new SignInError('bad', 'BAD_TOKEN');
|
||||
}
|
||||
},
|
||||
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
|
||||
if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE');
|
||||
return JSON.parse(raw.toString('utf8'));
|
||||
},
|
||||
}),
|
||||
} as unknown as AuthClientModule;
|
||||
}
|
||||
|
||||
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
|
||||
const db = memoryDb();
|
||||
const fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [] };
|
||||
const config = loadConfig({ WEBSITE_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
|
||||
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake) });
|
||||
await ctx.settings.set('hub_install_id', INSTALL_ID);
|
||||
if (opts.linked !== false) {
|
||||
await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt('link-secret'), connectedAt: new Date() } });
|
||||
}
|
||||
return { db, ctx, fake, app: createApp(ctx) };
|
||||
}
|
||||
|
||||
export type Harness = Awaited<ReturnType<typeof harness>> & { db: MemoryDb; ctx: Ctx };
|
||||
|
||||
/** `name=value` pairs from a response's Set-Cookie, for the next request. */
|
||||
export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Record<string, string> = {}): Record<string, string> {
|
||||
const out = { ...keep };
|
||||
for (const line of (res.headers['set-cookie'] as string[] | undefined) ?? []) {
|
||||
const [pair, ...attrs] = line.split(';');
|
||||
const i = pair!.indexOf('=');
|
||||
const name = pair!.slice(0, i).trim();
|
||||
const value = pair!.slice(i + 1).trim();
|
||||
const expired = attrs.some((a) => /^\s*expires=Thu, 01 Jan 1970/i.test(a)) || value === '';
|
||||
if (expired) delete out[name];
|
||||
else out[name] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* An in-memory stand-in for the Prisma client (from Accounts' tests/support/memoryDb.ts): every
|
||||
* model the Website uses, with the schema's defaults and unique fields, generic `where` matching
|
||||
* (equality, in / notIn, gt / gte / lt / lte, not, contains, AND / OR), `include` of the relations
|
||||
* below and `aggregate` sums. Enough to run the whole app in tests.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const DEFAULTS: Record<string, () => Row> = {
|
||||
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
|
||||
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
|
||||
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
|
||||
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
|
||||
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
|
||||
siteVersion: () => ({ note: null }),
|
||||
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
|
||||
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
|
||||
productLink: () => ({ connectedById: null, lastSyncError: null }),
|
||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
|
||||
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'], siteVersion: ['number'], page: ['slug'], message: ['slug', 'externalId'], previewLink: ['tokenHash'] };
|
||||
const HAS_UPDATED_AT = new Set(['siteDesign', 'page', 'section', 'ministry', 'leader', 'message', 'simpleEvent', 'appSetting', 'productLink']);
|
||||
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
||||
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||
page: { sections: { model: 'section', many: true, key: 'pageId' } },
|
||||
message: { series: { model: 'messageSeries', many: false, key: 'seriesId' } },
|
||||
};
|
||||
|
||||
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
||||
|
||||
function matchValue(actual: unknown, cond: unknown): boolean {
|
||||
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
||||
const c = cond as Record<string, unknown>;
|
||||
const insensitive = c.mode === 'insensitive';
|
||||
return Object.entries(c).every(([op, x]) => {
|
||||
switch (op) {
|
||||
case 'mode': return true;
|
||||
case 'equals': return v(actual) === v(x);
|
||||
case 'in': return (x as unknown[]).map(v).includes(v(actual));
|
||||
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
|
||||
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
|
||||
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
|
||||
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
|
||||
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
|
||||
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
||||
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
|
||||
default: throw new Error(`memoryDb: no operator ${op}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
return v(actual) === v(cond);
|
||||
}
|
||||
|
||||
export function matches(row: Row, where: Row = {}): boolean {
|
||||
return Object.entries(where ?? {}).every(([k, cond]) => {
|
||||
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
|
||||
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
|
||||
if (k === 'NOT') return !matches(row, cond as Row);
|
||||
return matchValue(row[k], cond);
|
||||
});
|
||||
}
|
||||
|
||||
const clone = <T>(x: T): T => structuredClone(x);
|
||||
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||
|
||||
function order(rows: Row[], orderBy?: Row | Row[]) {
|
||||
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
||||
return [...rows].sort((a, b) => {
|
||||
for (const o of list) {
|
||||
const [k, dir] = Object.entries(o)[0]!;
|
||||
const x = v(a[k]) as number;
|
||||
const y = v(b[k]) as number;
|
||||
const d = x < y ? -1 : x > y ? 1 : 0;
|
||||
if (d) return dir === 'desc' ? -d : d;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function prismaError(code: string, message: string) {
|
||||
return Object.assign(new Error(message), { code });
|
||||
}
|
||||
|
||||
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
const key = KEYS[name] ?? 'id';
|
||||
const table = () => {
|
||||
if (!tables.has(name)) tables.set(name, new Map());
|
||||
return tables.get(name)!;
|
||||
};
|
||||
const findWhere = (where: Row) => {
|
||||
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
||||
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
||||
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
||||
};
|
||||
const checkUnique = (row: Row, except?: unknown) => {
|
||||
for (const u of UNIQUE[name] ?? []) {
|
||||
if (row[u] == null) continue;
|
||||
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
|
||||
}
|
||||
};
|
||||
const api = {
|
||||
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
|
||||
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
||||
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
|
||||
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
|
||||
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
|
||||
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
|
||||
const rows = [...table().values()].filter((x) => matches(x, where));
|
||||
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
|
||||
},
|
||||
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
|
||||
create: async ({ data }: { data: Row }) => {
|
||||
const now = new Date();
|
||||
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
|
||||
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
|
||||
checkUnique(row);
|
||||
table().set(row[key], row);
|
||||
return clone(row);
|
||||
},
|
||||
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
|
||||
checkUnique(next, r[key]);
|
||||
table().set(r[key], next);
|
||||
return clone(next);
|
||||
},
|
||||
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
|
||||
return { count };
|
||||
},
|
||||
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
|
||||
const r = findWhere(where);
|
||||
return r ? api.update({ where, data: update }) : api.create({ data: create });
|
||||
},
|
||||
delete: async ({ where }: { where: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
|
||||
table().delete(r[key]);
|
||||
cascade(name, r[key]);
|
||||
return clone(r);
|
||||
},
|
||||
deleteMany: async ({ where }: { where?: Row } = {}) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
|
||||
return { count };
|
||||
},
|
||||
};
|
||||
const cascade = (from: string, id: unknown) => {
|
||||
if (from === 'page') for (const [k, r] of tables.get('section') ?? []) if (r.pageId === id) tables.get('section')!.delete(k);
|
||||
};
|
||||
const withIncludes = (row: Row, include?: Row) => {
|
||||
for (const [rel, on] of Object.entries(include ?? {})) {
|
||||
const spec = RELATIONS[name]?.[rel];
|
||||
if (!on || !spec) continue;
|
||||
const other = [...(tables.get(spec.model)?.values() ?? [])];
|
||||
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
|
||||
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
|
||||
}
|
||||
return row;
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
|
||||
|
||||
export function memoryDb(): MemoryDb {
|
||||
const tables = new Map<string, Map<unknown, Row>>();
|
||||
const models = new Map<string, ReturnType<typeof model>>();
|
||||
return new Proxy({} as MemoryDb, {
|
||||
get(_t, prop: string) {
|
||||
if (prop === 'tables') return tables;
|
||||
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
|
||||
if (prop === '$disconnect') return async () => {};
|
||||
if (prop === 'then') return undefined;
|
||||
if (!models.has(prop)) models.set(prop, model(prop, tables));
|
||||
return models.get(prop);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import {
|
||||
SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
|
||||
defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate,
|
||||
} from '../src/site/variants.js';
|
||||
|
||||
describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => {
|
||||
it('has the 26 confirmed variant ids', () => {
|
||||
assert.equal(Object.values(SECTION_VARIANTS).flat().length, 26);
|
||||
assert.deepEqual(SECTION_VARIANTS.hero, ['photo', 'video', 'collage', 'split', 'text']);
|
||||
});
|
||||
|
||||
it('every template recommends only real variants, without repeats, with a default for every section', () => {
|
||||
for (const t of WEBSITE_TEMPLATES) {
|
||||
for (const s of SECTION_TYPES) {
|
||||
const rec = TEMPLATE_VARIANTS[t][s] as readonly string[];
|
||||
assert.ok(rec.length >= 2, `${t}.${s}`);
|
||||
assert.equal(new Set(rec).size, rec.length, `${t}.${s} repeats`);
|
||||
for (const v of rec) assert.ok(isVariant(s, v), `${t}.${s}: ${v}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('has the confirmed defaults', () => {
|
||||
assert.equal(defaultVariant('heritage', 'hero'), 'photo');
|
||||
assert.equal(defaultVariant('bold', 'hero'), 'video');
|
||||
assert.equal(defaultVariant('community', 'hero'), 'collage');
|
||||
assert.equal(defaultVariant('clean', 'hero'), 'text');
|
||||
assert.equal(defaultVariant('clean', 'latestMessage'), 'compact');
|
||||
assert.ok(isRecommended('heritage', 'team', 'faces'));
|
||||
assert.ok(!isRecommended('heritage', 'team', 'list'));
|
||||
});
|
||||
|
||||
it('lists every section once in each homepage order; Bold hides Team, Clean hides Ministries and Team', () => {
|
||||
for (const t of WEBSITE_TEMPLATES) {
|
||||
assert.deepEqual([...TEMPLATE_HOME_ORDER[t].map((e) => e.section)].sort(), [...SECTION_TYPES].sort(), t);
|
||||
}
|
||||
const hidden = (t: keyof typeof TEMPLATE_HOME_ORDER) => TEMPLATE_HOME_ORDER[t].filter((e) => e.hidden).map((e) => e.section);
|
||||
assert.deepEqual(hidden('heritage'), []);
|
||||
assert.deepEqual(hidden('bold'), ['team']);
|
||||
assert.deepEqual(hidden('community'), []);
|
||||
assert.deepEqual(hidden('clean'), ['ministries', 'team']);
|
||||
});
|
||||
|
||||
it("each template's default header is the first of its options", () => {
|
||||
for (const t of WEBSITE_TEMPLATES) assert.equal(TEMPLATE_STYLE[t].header, TEMPLATE_HEADERS[t][0]);
|
||||
});
|
||||
|
||||
it('suggests the confirmed corners', () => {
|
||||
assert.deepEqual(WEBSITE_TEMPLATES.map((t) => TEMPLATE_STYLE[t].suggestedCorners), ['sharp', 'sharp', 'round', 'soft']);
|
||||
});
|
||||
|
||||
it('only makes the header transparent over a photo, video or collage hero', () => {
|
||||
assert.ok(headerIsTransparent('bold', 'transparent', 'video'));
|
||||
assert.ok(!headerIsTransparent('bold', 'transparent', 'text'));
|
||||
assert.ok(!headerIsTransparent('bold', 'transparent', 'split'));
|
||||
assert.ok(!headerIsTransparent('bold', 'solid', 'photo'));
|
||||
assert.ok(!headerIsTransparent('bold', 'transparent', null));
|
||||
});
|
||||
});
|
||||
|
||||
describe('switching template', () => {
|
||||
it('moves an untouched site to every default of the new template', () => {
|
||||
const { design, changes } = switchTemplate(defaultDesign('community'), 'clean');
|
||||
assert.deepEqual(design, defaultDesign('clean'));
|
||||
assert.ok(changes.some((c) => c.what === 'hero.variant' && c.from === 'collage' && c.to === 'text'));
|
||||
assert.ok(changes.some((c) => c.what === 'home'));
|
||||
assert.equal(changes[0]!.what, 'template');
|
||||
});
|
||||
|
||||
it("keeps the church's own choices", () => {
|
||||
const start = defaultDesign('heritage');
|
||||
start.variants.hero = 'video';
|
||||
start.style.buttons = 'pill';
|
||||
start.home = [...start.home].reverse();
|
||||
const { design, changes } = switchTemplate(start, 'clean');
|
||||
assert.equal(design.template, 'clean');
|
||||
assert.equal(design.variants.hero, 'video');
|
||||
assert.equal(design.style.buttons, 'pill');
|
||||
assert.deepEqual(design.home, start.home);
|
||||
assert.equal(design.variants.team, 'list', 'an untouched section still moves');
|
||||
assert.ok(!changes.some((c) => c.what === 'hero.variant' || c.what === 'home' || c.what === 'style.buttons'));
|
||||
});
|
||||
|
||||
it("moves a header the new template doesn't have", () => {
|
||||
const start = defaultDesign('bold');
|
||||
start.style.header = 'solid';
|
||||
const { design } = switchTemplate(start, 'heritage');
|
||||
assert.equal(design.style.header, 'centred');
|
||||
});
|
||||
|
||||
it('changes nothing when the template stays', () => {
|
||||
const d = defaultDesign('bold');
|
||||
assert.deepEqual(switchTemplate(d, 'bold'), { design: d, changes: [] });
|
||||
});
|
||||
|
||||
it('round-trips an untouched site', () => {
|
||||
const there = switchTemplate(defaultDesign('heritage'), 'bold').design;
|
||||
assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
// ES modules throughout, as Accounts (docs/WEBSITE-1.0-PLAN.md §1).
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"lib": ["ES2023"],
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"sourceMap": true,
|
||||
"rootDir": ".",
|
||||
"outDir": "dist",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "tests", "scripts", "prisma.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// PM2 config template. Each install keeps its own copy as ecosystem.config.cjs (not in git, so
|
||||
// deploys never change it); crosscode creates it from this file the first time with the church's
|
||||
// PM2 names and ports.
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'website-backend',
|
||||
cwd: __dirname + '/backend',
|
||||
script: 'dist/index.js',
|
||||
env: { NODE_ENV: 'production' },
|
||||
max_memory_restart: '400M',
|
||||
},
|
||||
{
|
||||
name: 'website-frontend',
|
||||
cwd: __dirname + '/frontend',
|
||||
script: 'npm',
|
||||
args: 'start -- -p 3300',
|
||||
env: { NODE_ENV: 'production' },
|
||||
max_memory_restart: '400M',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema": "crosscode.env-template/1",
|
||||
"product": "website",
|
||||
"files": {
|
||||
"backend/.env": [
|
||||
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
|
||||
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
|
||||
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
|
||||
{ "name": "WEBSITE_SECRET", "layer": "generated", "required": true, "description": "Signs preview links and cookies, encrypts stored secrets: never change it" },
|
||||
{ "name": "WEBSITE_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address (www. or the Cross Code address)" },
|
||||
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
|
||||
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg" },
|
||||
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
|
||||
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
|
||||
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCW-…)" },
|
||||
{ "name": "HUB_ADMIN_NAME", "layer": "install" },
|
||||
{ "name": "HUB_ADMIN_EMAIL", "layer": "install", "description": "The first person to sign in with this address (through Accounts, verified) becomes the Owner" },
|
||||
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
.next/
|
||||
next-env.d.ts
|
||||
.env*
|
||||
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
// Next.js 16's own flat configs, as Accounts. Run with `npm run lint`.
|
||||
export default defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
|
||||
]);
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
// Everything under /api is the backend (docs/WEBSITE-1.0-PLAN.md §1). On a server nginx sends it
|
||||
// there; in development (and when Next is reached directly) this rewrite does.
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
poweredByHeader: false,
|
||||
transpilePackages: ["@crosscode/ui"],
|
||||
async rewrites() {
|
||||
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
|
||||
},
|
||||
async headers() {
|
||||
// The public site is indexed (ROADMAP-v3 §11); the admin and shared previews never are.
|
||||
const common = [
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
];
|
||||
const noindex = { key: "X-Robots-Tag", value: "noindex, nofollow" };
|
||||
return [
|
||||
{ source: "/:path*", headers: common },
|
||||
{ source: "/admin/:path*", headers: [noindex] },
|
||||
{ source: "/admin", headers: [noindex] },
|
||||
{ source: "/preview/:path*", headers: [noindex] },
|
||||
{ source: "/auth/:path*", headers: [noindex] },
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Church Website: the church's public site in its template, and the admin",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3300",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint src",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"next": "^16.4.6",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "3.4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Metadata } from "next";
|
||||
import { redirect } from "next/navigation";
|
||||
import { loadMe, ROLE_NAMES, signInHref } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// The admin (docs/WEBSITE-1.0-PLAN.md §10), signed in through the church's Accounts. The screens
|
||||
// (template and style, pages, messages, events, publish) come next.
|
||||
export default async function Admin() {
|
||||
const me = await loadMe();
|
||||
if (!me) redirect(signInHref("/admin"));
|
||||
return (
|
||||
<main className="mx-auto max-w-xl px-4 py-16">
|
||||
<h1 className="text-2xl font-semibold">Website admin</h1>
|
||||
<p className="mt-2 text-gray-600">
|
||||
Signed in as {me.user.name} ({me.user.email}), {ROLE_NAMES[me.user.role]}.
|
||||
</p>
|
||||
<form method="post" action="/api/auth/signout" className="mt-6">
|
||||
<button type="submit" className="rounded border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Sign out
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { signInHref } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Signing in", robots: { index: false, follow: false } };
|
||||
|
||||
/** What went wrong with a sign-in (the backend's auth/routes.ts sends people here with a code). */
|
||||
const PROBLEMS: Record<string, { title: string; text: string; retry: boolean }> = {
|
||||
NO_ACCESS: {
|
||||
title: "No access to this website's admin",
|
||||
text: "You're signed in, but your account hasn't been given a role on this website. Ask the website's Owner to add you, then try again.",
|
||||
retry: true,
|
||||
},
|
||||
TWO_FACTOR_NEEDED: {
|
||||
title: "Two-step sign-in needed",
|
||||
text: "Owners and Admins of this website sign in with a second step. Turn on two-step sign-in in your church account, then try again.",
|
||||
retry: true,
|
||||
},
|
||||
ACCOUNTS_UNAVAILABLE: {
|
||||
title: "Signing in isn't available right now",
|
||||
text: "The website can't reach your church's sign-in at the moment. Please try again in a few minutes.",
|
||||
retry: true,
|
||||
},
|
||||
EXPIRED: { title: "The sign-in took too long", text: "Please try again.", retry: true },
|
||||
SIGNIN_FAILED: { title: "That didn't work", text: "Something went wrong while signing you in. Please try again.", retry: true },
|
||||
};
|
||||
|
||||
export default async function Problem({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
|
||||
const q = await searchParams;
|
||||
const code = typeof q.code === "string" ? q.code : "";
|
||||
const returnTo = typeof q.returnTo === "string" && q.returnTo.startsWith("/") && !q.returnTo.startsWith("//") ? q.returnTo : "/admin";
|
||||
const p = PROBLEMS[code] ?? PROBLEMS.SIGNIN_FAILED!;
|
||||
return (
|
||||
<main className="mx-auto max-w-xl px-4 py-16">
|
||||
<h1 className="text-2xl font-semibold">{p.title}</h1>
|
||||
<p className="mt-2 text-gray-600">{p.text}</p>
|
||||
<div className="mt-6 flex gap-3">
|
||||
{p.retry && (
|
||||
<a href={signInHref(returnTo)} className="rounded bg-brand px-4 py-2 text-sm text-white hover:bg-brand-dark">
|
||||
Try again
|
||||
</a>
|
||||
)}
|
||||
<Link href="/" className="rounded border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Go to the website
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Defaults until the church profile's colour is set (layout.tsx overrides them per request). */
|
||||
:root {
|
||||
--brand: 31 78 121;
|
||||
--brand-dark: 21 55 85;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-white text-gray-900 antialiased;
|
||||
/* The church's font pairing (@crosscode/ui fonts.css); the template's default until it picks one. */
|
||||
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif);
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
|
||||
// The church's name, colours, fonts and corners come from its profile in Accounts once the Website
|
||||
// is linked (docs/WEBSITE-1.0-PLAN.md §2); until then, plain defaults.
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "Church Website", template: "%s" },
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en-ZA" {...brandAttributes(null)}>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Metadata } from "next";
|
||||
import { loadStatus } from "@/lib/site";
|
||||
|
||||
// Rendered per request from the backend's status; the published site is cached once it exists (§1).
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const status = await loadStatus();
|
||||
// Coming soon is a real page (HTTP 200) but never indexed (§5, decision 14).
|
||||
return status.mode === "coming-soon" ? { title: "Coming soon", robots: { index: false, follow: true } } : { title: "Home" };
|
||||
}
|
||||
|
||||
export default async function Home() {
|
||||
const status = await loadStatus();
|
||||
if (status.mode === "coming-soon") {
|
||||
// The full Coming soon page (logo, service times, contact, links to Events) comes with the
|
||||
// church profile (§5).
|
||||
return (
|
||||
<main className="mx-auto flex min-h-screen max-w-xl flex-col items-center justify-center gap-4 px-4 text-center">
|
||||
<h1 className="text-3xl font-semibold text-brand">Coming soon</h1>
|
||||
<p className="text-gray-600">Our new website is on its way.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-16">
|
||||
<h1 className="text-3xl font-semibold">Welcome</h1>
|
||||
<p className="mt-2 text-gray-600">Published version {status.version}. The templates come next (§3).</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
|
||||
// The public site is indexed; the admin, previews and API never are (ROADMAP-v3 §11). The sitemap
|
||||
// comes with the published pages.
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return { rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/preview", "/auth", "/api"] }] };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
/** The signed-in admin (from the backend's /api/auth/me), for the admin's server-rendered pages. */
|
||||
export type Me = {
|
||||
user: { id: string; name: string; email: string; role: "owner" | "admin" | "editor" | "ministry_leader" | "viewer"; ministryId: string | null };
|
||||
mfa: boolean;
|
||||
};
|
||||
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
export const ROLE_NAMES: Record<Me["user"]["role"], string> = {
|
||||
owner: "Owner",
|
||||
admin: "Admin",
|
||||
editor: "Editor",
|
||||
ministry_leader: "Ministry leader",
|
||||
viewer: "Viewer",
|
||||
};
|
||||
|
||||
/** Null when signed out (or the backend can't say); the page then sends people to sign in. */
|
||||
export async function loadMe(): Promise<Me | null> {
|
||||
const session = (await cookies()).get("ccw_session")?.value;
|
||||
if (!session) return null;
|
||||
try {
|
||||
const res = await fetch(`${api}/api/auth/me`, { headers: { Cookie: `ccw_session=${encodeURIComponent(session)}` }, cache: "no-store" });
|
||||
if (res.ok) return (await res.json()) as Me;
|
||||
} catch {
|
||||
// The backend is starting or down: treated as signed out.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Where "Sign in" goes for a page of the admin: Accounts, and back to that page. */
|
||||
export const signInHref = (returnTo: string) => `/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}`;
|
||||
@@ -0,0 +1,16 @@
|
||||
/** What the public site shows right now, from the backend (src/site/status.ts there). */
|
||||
export type SiteStatus =
|
||||
| { mode: "coming-soon" }
|
||||
| { mode: "published"; version: number; publishedAt: string; template: string | null };
|
||||
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
export async function loadStatus(): Promise<SiteStatus> {
|
||||
try {
|
||||
const res = await fetch(`${api}/api/v1/site/status`, { next: { revalidate: 30 } });
|
||||
if (res.ok) return (await res.json()) as SiteStatus;
|
||||
} catch {
|
||||
// The backend is starting or down: Coming soon is the safe thing to show.
|
||||
}
|
||||
return { mode: "coming-soon" };
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
// The church's colours are CSS variables set per request in layout.tsx (from the church profile).
|
||||
module.exports = {
|
||||
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: { DEFAULT: "rgb(var(--brand) / <alpha-value>)", dark: "rgb(var(--brand-dark) / <alpha-value>)" },
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -2,5 +2,5 @@
|
||||
"name": "@crosscode/website",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": "Placeholder: Church Website, built in phase 5 (ROADMAP-v3 §6)"
|
||||
"description": "Church Website (ROADMAP-v3 §6, phase 5): backend/ and frontend/ are the workspaces"
|
||||
}
|
||||
|
||||
+7
-10
@@ -1,6 +1,6 @@
|
||||
# Handover — Cross Code, all products
|
||||
|
||||
Last updated: 2026-11-24. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
Last updated: 2026-11-25. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
decisions table near the end). This file says where each phase stands and what comes next.
|
||||
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
|
||||
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
|
||||
@@ -32,9 +32,9 @@ every release).
|
||||
| 1d | Agent 1.x + Hub 2.1+ | **Released, rolled out and tested** (agent `1.5.0` on every server: from 1.4.0 the Hub reads and changes frps's / frpc's config and probes ports before an install; from 1.5.0 one product of a church can be uninstalled, exported or purged) |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | **Released, rolled out and tested** ([EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)) |
|
||||
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.6.1`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.7.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
|
||||
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
|
||||
| 5 | Church Website 1.0.0 | **Planned** 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (all decisions confirmed). Font pairings confirmed 2026-11-24 (§3). `contracts@1.17.0` and `accounts@1.7.0` released 2026-11-24 (Accounts not yet rolled out); Events 3.7.0 next |
|
||||
| 5 | Church Website 1.0.0 | **Planned** 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md) (all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet); `website@1.0.0` next |
|
||||
| 6–7 | App 1.0.0 → App 1.x | Not started |
|
||||
|
||||
## Released 2026-11-23
|
||||
@@ -101,14 +101,11 @@ out").
|
||||
1. **Phase 5, Church Website 1.0.0** (ROADMAP §6, §9). Planned in
|
||||
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
|
||||
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
|
||||
ships with contracts because it answers the new `church.update`) → Events 3.7.0 (shared fonts and footer) → **Hub 2.21.0** (the
|
||||
plan said 2.13.0; the Hub has moved on since) → `website@1.0.0` → Hope Family Church → a second
|
||||
ships with contracts because it answers the new `church.update`) → ~~Events 3.7.0~~ (shared fonts and footer; released 2026-11-24) → ~~Hub 2.21.0~~ (released
|
||||
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (skeleton in `apps/website` 2026-11-25: backend, frontend, content model, the section variants in `src/site/variants.ts`) → Hope Family Church → a second
|
||||
church → crosscode-site 1.7.0.
|
||||
2. **Archive `hope-events`** if it isn't yet (every install now reports 2.2.0 or later;
|
||||
EVENTS-2.2-PLAN §7).
|
||||
3. **FastPanel sites set up before Hub 2.10.0** need `location ^~ /api/` by hand, and so does the
|
||||
Hub's own site ("FastPanel sites" above). Not yet recorded which are done: check each with
|
||||
`curl -sI https://<domain>/api/health.png`.
|
||||
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
|
||||
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
|
||||
|
||||
## The VM test (2026-11-17)
|
||||
|
||||
|
||||
+16
-5
@@ -10,11 +10,11 @@ separately below; the two often differ.
|
||||
|
||||
| What | Repo | Latest | Tag | Released |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.6.1** | `events@3.6.1` | 2026-11-20 |
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.0** | `events@3.7.0` | 2026-11-24 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.7.0** | `accounts@1.7.0` | 2026-11-24 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.5.0** | `agent@1.5.0` | 2026-11-23 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.17.0** | `contracts@1.17.0` | 2026-11-24 |
|
||||
| Cross Code Hub | `events-hub` | **2.20.0** | `v2.20.0` | 2026-11-23 |
|
||||
| Cross Code Hub | `events-hub` | **2.21.0** | `v2.21.0` | 2026-11-25 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.6.1** | `v1.6.1` | 2026-11-23 |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
|
||||
|
||||
@@ -28,8 +28,8 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
|
||||
|------|-------|-------------------------|
|
||||
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
|
||||
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
|
||||
| `@crosscode/ui` | `packages/ui` | 0.2.0 (fonts, `ChurchFooter`; released with Accounts 1.7.0) |
|
||||
| Website | `apps/website` | 0.0.0 (phase 5, being built: contracts 1.17.0 released) |
|
||||
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
|
||||
| Website | `apps/website` | 0.1.0 (phase 5, being built: skeleton 2026-11-25; backend and frontend workspaces) |
|
||||
| App | `apps/app` | 0.0.0 (not started, phase 6) |
|
||||
|
||||
These shared packages ship inside the apps that use them, from the same checkout, so they don't
|
||||
@@ -37,6 +37,17 @@ need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Hub 2.21.0 (2026-11-25):** New install offers the Church Website (Accounts first, at
|
||||
`accounts.<its address>`); the FastPanel email sends a `www.` site's bare domain to `www.` with a
|
||||
301. Extra Website storage is bought in 5 GB steps on the licence (Edit → Extra storage), sent to
|
||||
the site as its limit (`limits.storageBytes`) and billed on the steps bought, no longer on usage.
|
||||
Vendors contracts 1.17.0. **Migration:** `Licence.extraStorageSteps`. "Get more storage" comes
|
||||
with the Website (contracts 1.18.0). **Deployed 2026-11-25.**
|
||||
- **Events 3.7.0 (2026-11-24):** the public pages use the church's fonts, corners and the shared
|
||||
church footer from its profile in Accounts (`GET /api/v2/church`, kept 10 minutes), with links to
|
||||
its other sites in the header; `church.changed` from Accounts is now accepted (it answered 404
|
||||
before). The dashboard and setup screens are unchanged. `@crosscode/ui` 0.3.0. No migrations.
|
||||
Requires Accounts 1.7.0 (the Hub updates it first). **Not deployed yet.**
|
||||
- **Contracts 1.17.0 + Accounts 1.7.0 (2026-11-24):** the first piece of the Church Website. Contracts:
|
||||
the 8 font pairings, corner styles and template ids (`./style`), an optional `branding.style` on the
|
||||
church profile, `church.update` (the Website changes shared profile facts), an optional `website`
|
||||
@@ -212,7 +223,7 @@ you deploy one.
|
||||
|
||||
| What | Running | Since | Notes |
|
||||
|------|---------|-------|-------|
|
||||
| Hub | 2.20.0 | 2026-11-23 | Port list says what each port is for; hand-written frpc tunnels listed as taken; frps allow_ports checked against the port list (no migration) |
|
||||
| Hub | 2.21.0 | 2026-11-25 | Church Website in New install; `www.` redirect in the FastPanel email; extra Website storage on the licence (migration `Licence.extraStorageSteps`); vendors contracts 1.17.0 |
|
||||
| Agent on church-server1 | 1.5.0 | 2026-11-23 | Uninstalls one product of a church at a time |
|
||||
| Agent on the central server | 1.5.0 | 2026-11-23 | Reads and changes frps's config from the Hub (no longer read-only; decision 35 superseded) |
|
||||
| Cross Events (churches) | 3.6.1 | 2026-11-20 | Every install adopted onto the monorepo and signing in through Accounts |
|
||||
|
||||
+137
-2
@@ -2,12 +2,15 @@
|
||||
|
||||
Phase **5** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§6, §9, §10, §11; decisions 19, 20, 40–47).
|
||||
Written 2026-11-21. **All decisions confirmed by Joshua on 2026-11-21** (12 changed: a full
|
||||
storage stops uploads). Not started.
|
||||
storage stops uploads). **Being built:** the skeleton is in `apps/website` (2026-11-25).
|
||||
|
||||
**Updated 2026-11-24:** the Hub release is **2.21.0**, not 2.13.0 (the Hub reached 2.20.0 on
|
||||
2026-11-23 with other work). The 8 font pairings in §3 ("Font pairings") were **confirmed by Joshua
|
||||
on 2026-11-24** (decision 15).
|
||||
|
||||
**Updated 2026-11-25:** the **section variants per template** in §3 were confirmed by Joshua
|
||||
(decision 16).
|
||||
|
||||
**What the Website is:** the church's public site at `www.<church's address>` (or
|
||||
`<church>.crosscode.co.za` on the Cross Code address), plus its admin at `/admin`. Admins sign in
|
||||
through the church's Accounts. The church picks one of **four templates** and makes it its own with
|
||||
@@ -210,6 +213,126 @@ files, slower), and very thin display faces (fail contrast at small sizes).
|
||||
Events and Accounts keep the system fonts they use now, so Events 3.7 and Accounts 1.7 look the same
|
||||
until an admin picks a pairing. `corners` missing means `soft`.
|
||||
|
||||
### Section variants per template (confirmed 2026-11-25)
|
||||
|
||||
Answers "Still open: the exact section variants per template". The rule from the table above stays:
|
||||
**every template renders every variant**, so no choice is ever greyed out and switching template
|
||||
never needs a fallback. What a template adds is (a) which variant each section **starts with**,
|
||||
(b) which variants it **recommends** (shown first, marked "Suits Heritage"), and (c) **how it draws**
|
||||
each one. Variant ids are stored on the section (`hero.variant = "photo"`), so like the font ids
|
||||
they never change once released.
|
||||
|
||||
**Variant ids**
|
||||
|
||||
| Section | Ids |
|
||||
|---|---|
|
||||
| Hero | `photo` · `video` · `collage` · `split` · `text` |
|
||||
| Service times and location | `panel` · `strip` · `map` |
|
||||
| Welcome / introduction | `text` · `image-text` · `pastor` |
|
||||
| Ministries | `cards` · `list` · `bands` |
|
||||
| Team / leaders | `faces` · `list` · `featured` |
|
||||
| Upcoming events | `cards` · `list` · `calendar` |
|
||||
| Latest message | `video` · `card` · `compact` |
|
||||
| Invitation | `banner` · `centred` · `image` |
|
||||
|
||||
The mission line (ROADMAP §6's homepage order) is a field of the Welcome section, shown above the
|
||||
introduction in every variant, not a section of its own.
|
||||
|
||||
**Defaults and recommendations** (default first, then the other recommended ones; anything not listed
|
||||
still works)
|
||||
|
||||
| Section | Heritage | Bold | Community | Clean |
|
||||
|---|---|---|---|---|
|
||||
| Hero | **`photo`** (framed), `split`, `text` | **`video`**, `photo`, `split` | **`collage`**, `photo`, `split` | **`text`**, `split`, `photo` |
|
||||
| Service times | **`panel`**, `map` | **`strip`**, `map` | **`map`**, `panel` | **`strip`**, `panel` |
|
||||
| Welcome | **`pastor`**, `text` | **`image-text`**, `pastor` | **`pastor`**, `image-text` | **`text`**, `image-text` |
|
||||
| Ministries | **`list`**, `cards` | **`bands`**, `cards` | **`cards`**, `bands` | **`list`**, `cards` |
|
||||
| Team | **`featured`**, `faces` | **`faces`**, `featured` | **`faces`**, `featured` | **`list`**, `faces` |
|
||||
| Events | **`list`**, `calendar` | **`cards`**, `calendar` | **`cards`**, `calendar` | **`list`**, `calendar` |
|
||||
| Latest message | **`card`**, `video` | **`video`**, `card` | **`card`**, `video` | **`compact`**, `card` |
|
||||
| Invitation | **`centred`**, `banner` | **`image`**, `banner` | **`banner`**, `image` | **`centred`**, `banner` |
|
||||
|
||||
**How each template draws them**
|
||||
|
||||
- **Heritage** (traditional, single centred column, thin rules between sections):
|
||||
`photo` sits *inside* a frame below the centred logo and navigation, never full-bleed; `video` is
|
||||
framed the same way. `collage` is three framed photos in a row. `split` keeps the image in a
|
||||
frame with text on the cream side. `panel` is the formal service-times panel with a double rule.
|
||||
`cards` are bordered, square-ish, with serif titles; `bands` alternate within the column width
|
||||
rather than full-bleed. `faces` are circular portraits with names in small caps. `calendar` is a
|
||||
month list with dates set in the heading font.
|
||||
- **Bold** (full-bleed, large type, sticky header): `photo` and `video` fill the screen with the
|
||||
headline overlaid on a scrim (contrast checked against the image's dark-scrim colour, not the
|
||||
photo); `collage` is an edge-to-edge mosaic. `split` is 50/50 full-bleed. `strip` is a coloured
|
||||
band right under the hero. `bands` are full-bleed alternating image / text. `cards` are large,
|
||||
image-led, with the title on the image. `faces` are tall portrait crops. `text` hero is a huge
|
||||
headline on the primary colour.
|
||||
- **Community** (cards, soft shapes, tinted backgrounds, faces prominent): `collage` is overlapping
|
||||
rounded photos with a soft blob shape behind; `photo` gets a curved bottom edge. Every list-like
|
||||
section prefers a card grid; `list` still exists but with rounded rows and small thumbnails.
|
||||
`map` shows the map in a rounded card next to the times. `faces` are big, with role and a short
|
||||
line. Sections alternate light and tinted backgrounds by default (Section colour `tinted`).
|
||||
- **Clean** (small header, white space, narrow column, colour as accent): `text` hero is the church's
|
||||
headline in large type with the service time underneath, no image needed. `photo` is shown
|
||||
*below* the headline at column width, never behind text. `video` is a contained player, never
|
||||
autoplaying as a background. `strip` is one line of text with a thin accent rule. `cards` are
|
||||
borderless with a hairline separator. `collage` is a tidy three-image grid. `bands` become
|
||||
stacked image / text pairs within the column.
|
||||
|
||||
**Headers** (the "Header" style setting)
|
||||
|
||||
| Template | Options (default first) |
|
||||
|---|---|
|
||||
| Heritage | **Centred** (logo above, navigation below) · Centred with a top bar (service time and Plan your visit) |
|
||||
| Bold | **Transparent over the hero, solid on scroll** · Solid |
|
||||
| Community | **Logo left, navigation right, Plan your visit button** · Same with a tinted bar |
|
||||
| Clean | **Small, logo left, text navigation** · Small with navigation in a menu on every width |
|
||||
|
||||
Every header collapses to a menu button on phones; the transparent one only applies when the page
|
||||
starts with a `photo`, `video` or `collage` hero (otherwise it's solid, so it never sits on white
|
||||
text over white).
|
||||
|
||||
**Default homepage order** (the church can reorder, hide and show)
|
||||
|
||||
| Template | Order |
|
||||
|---|---|
|
||||
| Heritage | Hero · Service times · Welcome · Latest message · Ministries · Team · Events · Invitation |
|
||||
| Bold | Hero · Service times · Welcome · Events · Latest message · Ministries · Invitation (Team hidden) |
|
||||
| Community | Hero · Welcome · Service times · Ministries · Team · Events · Latest message · Invitation |
|
||||
| Clean | Hero · Service times · Welcome · Events · Latest message · Invitation (Ministries and Team hidden) |
|
||||
|
||||
**Style defaults when a template is picked** (the church changes them afterwards)
|
||||
|
||||
| Template | Section colour | Spacing | Buttons | Images | Corners (if the profile has none) |
|
||||
|---|---|---|---|---|---|
|
||||
| Heritage | Light | Airy | Outline | Natural | `sharp` |
|
||||
| Bold | Mixed with dark bands | Compact | Solid | Natural | `sharp` |
|
||||
| Community | Tinted | Airy | Pill | Natural | `round` |
|
||||
| Clean | Light | Airy | Outline | Natural | `soft` |
|
||||
|
||||
Corners and the font pairing are shared (roadmap decision 47), so picking a
|
||||
template only *suggests* them when the profile has none; it never overwrites a church's existing
|
||||
brand style without the admin saying yes ("Use Heritage's fonts and corners for all your sites?").
|
||||
|
||||
**Switching template** (§4, a pending change like any other):
|
||||
|
||||
- A section still on the **old template's default** moves to the **new template's default**, so a
|
||||
church that never touched variants gets the new template's intended look.
|
||||
- A section the church **chose a variant for** keeps it (every template draws every variant).
|
||||
- The homepage order and hidden sections are kept if the church changed them; otherwise the new
|
||||
template's default order applies.
|
||||
- Style settings follow the same rule: untouched ones take the new template's defaults, changed ones
|
||||
stay. The Publish screen lists what moved ("Hero: Collage → Text only, Clean's default").
|
||||
|
||||
**Blocks on custom pages** use the same ids where they overlap (image and text: `image-text`,
|
||||
people cards: `faces` / `list` / `featured`, call to action: `banner` / `centred` / `image`); the
|
||||
other blocks (text, gallery, quote, video, FAQ, map, divider) have one layout each, drawn in the
|
||||
template's style.
|
||||
|
||||
**Checks per variant:** the Playwright screenshots and axe run (§13) cover **every variant in every
|
||||
template** for the homepage sections (26 section variants × 4 templates × 3 widths = 312
|
||||
screenshots), using the demo church, plus a run with each template's defaults for Lighthouse.
|
||||
|
||||
## 4. Drafts, preview and publish
|
||||
|
||||
Decision 2: **one Publish for the whole site.**
|
||||
@@ -333,6 +456,11 @@ preview and SEO warnings where they apply (ROADMAP §11).
|
||||
Admin roles can require 2FA through Accounts (`acr_values=mfa`, ACCOUNTS-1.0-PLAN decision 8): on by
|
||||
default for Owner and Admin.
|
||||
|
||||
**The first Owner** (built 2026-11-25, to confirm): whoever signs in through Accounts with the
|
||||
church's admin email from the Hub (`HUB_ADMIN_EMAIL`, as Accounts' setup uses it), with that email
|
||||
verified in Accounts, while the site has no Owner. Everyone else is added by an Owner or Admin. If
|
||||
the last Owner's account is deleted, the same rule finds the next one.
|
||||
|
||||
**Storage** (ROADMAP §10): 5 GB of uploads included. Settings shows what's used; admins get an email
|
||||
at 80% and at 100%. **When it's full, uploads stop** (decision 12) until more storage is bought:
|
||||
the media library and every upload field say so, with **Get more storage** (Settings → Storage).
|
||||
@@ -451,8 +579,15 @@ Confirmed on 2026-11-24:
|
||||
`friendly`, `warm`, `modern`, three recommended per template. A church without one keeps
|
||||
the system fonts in Events and Accounts; `corners` defaults to `soft`.
|
||||
|
||||
Confirmed on 2026-11-25:
|
||||
|
||||
16. **Section variants per template** in §3: every template draws every variant (26 variant ids,
|
||||
fixed once released), with a default and recommendations per template; per-template headers,
|
||||
homepage order (Bold hides Team, Clean hides Ministries and Team) and style defaults; picking a
|
||||
template only suggests the shared fonts and corners; a template switch moves untouched sections
|
||||
and settings to the new defaults and keeps the church's own choices.
|
||||
|
||||
## Still open
|
||||
|
||||
- The exact section variants per template: settled with the template designs, early in the build.
|
||||
- Whether the App (phase 6) moves leaders, ministries and giving into `crosscode.church/1` or reads
|
||||
them from the Website. Decide with the App plan.
|
||||
|
||||
+2
-2
@@ -18,6 +18,6 @@ export default defineConfig([
|
||||
},
|
||||
},
|
||||
// Cross Events keeps its own lint (frontend/eslint.config.mjs, tsc for the backend) for now.
|
||||
// The Accounts frontend has its own Next lint (apps/accounts/frontend/eslint.config.mjs); Prisma's client is generated.
|
||||
globalIgnores(["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/schemas/**", "apps/events/**", "apps/accounts/frontend/**", "**/src/generated/**", "**/.next/**"]),
|
||||
// The Accounts and Website frontends have their own Next lint (apps/*/frontend/eslint.config.mjs); Prisma's client is generated.
|
||||
globalIgnores(["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/schemas/**", "apps/events/**", "apps/accounts/frontend/**", "apps/website/frontend/**", "**/src/generated/**", "**/.next/**"]),
|
||||
]);
|
||||
|
||||
Generated
+69
-9
@@ -12,10 +12,13 @@
|
||||
"apps/*",
|
||||
"!apps/events",
|
||||
"!apps/accounts",
|
||||
"!apps/website",
|
||||
"apps/events/backend",
|
||||
"apps/events/frontend",
|
||||
"apps/accounts/backend",
|
||||
"apps/accounts/frontend"
|
||||
"apps/accounts/frontend",
|
||||
"apps/website/backend",
|
||||
"apps/website/frontend"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.14.0",
|
||||
@@ -46,7 +49,7 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
@@ -83,7 +86,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -128,7 +131,7 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
@@ -178,10 +181,11 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@hookform/resolvers": "^5.2.1",
|
||||
"@radix-ui/react-accordion": "^1.2.11",
|
||||
@@ -347,7 +351,59 @@
|
||||
},
|
||||
"apps/website": {
|
||||
"name": "@crosscode/website",
|
||||
"version": "0.0.0"
|
||||
"version": "0.0.0",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"apps/website/backend": {
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "0.1.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"prisma": "^7.10.1",
|
||||
"supertest": "^7.3.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
},
|
||||
"apps/website/frontend": {
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"next": "^16.4.6",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "3.4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
},
|
||||
"node_modules/@alloc/quick-lru": {
|
||||
"version": "5.3.0",
|
||||
@@ -1019,8 +1075,12 @@
|
||||
"resolved": "packages/ui",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/website": {
|
||||
"resolved": "apps/website",
|
||||
"node_modules/@crosscode/website-backend": {
|
||||
"resolved": "apps/website/backend",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/website-frontend": {
|
||||
"resolved": "apps/website/frontend",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@date-fns/tz": {
|
||||
@@ -21436,7 +21496,7 @@
|
||||
},
|
||||
"packages/ui": {
|
||||
"name": "@crosscode/ui",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/dm-sans": "5.3.0",
|
||||
"@fontsource-variable/eb-garamond": "5.3.0",
|
||||
|
||||
+5
-2
@@ -8,10 +8,13 @@
|
||||
"apps/*",
|
||||
"!apps/events",
|
||||
"!apps/accounts",
|
||||
"!apps/website",
|
||||
"apps/events/backend",
|
||||
"apps/events/frontend",
|
||||
"apps/accounts/backend",
|
||||
"apps/accounts/frontend"
|
||||
"apps/accounts/frontend",
|
||||
"apps/website/backend",
|
||||
"apps/website/frontend"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "npm run build --workspaces --if-present",
|
||||
@@ -19,7 +22,7 @@
|
||||
"test:scripts": "bats scripts/tests",
|
||||
"typecheck": "npm run typecheck --workspaces --if-present",
|
||||
"lint": "eslint .",
|
||||
"lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh scripts/products/accounts.sh scripts/lib/report.sh scripts/lib/env.sh scripts/lib/frpc.sh scripts/lib/manage.sh apps/agent/deploy/install.sh apps/agent/deploy/revert.sh",
|
||||
"lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh scripts/products/accounts.sh scripts/products/website.sh scripts/lib/report.sh scripts/lib/env.sh scripts/lib/frpc.sh scripts/lib/manage.sh apps/agent/deploy/install.sh apps/agent/deploy/revert.sh",
|
||||
"check": "npm run lint && npm run lint:scripts && npm run typecheck && npm test && npm run test:scripts && npm run build"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/ui",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"private": true,
|
||||
"description": "Shared UI for the church's sign-in pages, Website and App: the branded shell, forms and buttons, the church's fonts and footer (Tailwind; apps compile the source with transpilePackages)",
|
||||
"main": "src/index.tsx",
|
||||
|
||||
@@ -57,9 +57,10 @@ export function productLinks(links: FooterChurch["links"], current: FooterProduc
|
||||
/**
|
||||
* One footer for every product: the church's name and logo, service times, address and contact,
|
||||
* social links, links to its other sites, and the privacy notice. Sections without data are left
|
||||
* out. `className` lets a Website template restyle it.
|
||||
* out. `className` lets a Website template restyle it; `bottom` goes after the copyright line (a
|
||||
* product's own links, such as its terms and cookie settings).
|
||||
*/
|
||||
export function ChurchFooter({ church, current, privacyUrl, className }: { church: FooterChurch; current: FooterProduct; privacyUrl?: string | null; className?: string }) {
|
||||
export function ChurchFooter({ church, current, privacyUrl, className, bottom }: { church: FooterChurch; current: FooterProduct; privacyUrl?: string | null; className?: string; bottom?: React.ReactNode }) {
|
||||
const times = church.serviceTimes ?? [];
|
||||
const contact = church.contact;
|
||||
const address = contact?.address;
|
||||
@@ -110,7 +111,10 @@ export function ChurchFooter({ church, current, privacyUrl, className }: { churc
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
<p className="px-4 pb-6 text-center text-xs text-gray-500">© {new Date().getFullYear()} {church.name}</p>
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1 px-4 pb-6 text-center text-xs text-gray-500">
|
||||
<p>© {new Date().getFullYear()} {church.name}</p>
|
||||
{bottom}
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
|
||||
+1
-1
@@ -92,7 +92,7 @@ crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" r
|
||||
crosscode deploy <church> … --check only the checks; changes nothing
|
||||
crosscode status [<church>] versions, latest releases, health
|
||||
crosscode install <church> --products events --domain <address> a new church
|
||||
crosscode add <church> accounts [--domain …] add a product to a church here
|
||||
crosscode add <church> accounts|website [--domain …] add a product to a church here
|
||||
crosscode adopt <church> --events-dir <old folder> move an existing Cross Events install here
|
||||
crosscode adopt <church> --undo go back to the old folder (within 14 days)
|
||||
crosscode restart <church> [events] reload the PM2 processes
|
||||
|
||||
@@ -8,7 +8,7 @@ CROSSCODE_REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode
|
||||
# through it.
|
||||
PRODUCT_ORDER=(accounts events website app)
|
||||
# Products this version of the script can deploy (a products/<name>.sh exists for each).
|
||||
SUPPORTED_PRODUCTS=(accounts events)
|
||||
SUPPORTED_PRODUCTS=(accounts events website)
|
||||
# Releases older than this get a warning; older than CROSSCODE_NODE_MIN the deploy is refused.
|
||||
CROSSCODE_NODE_MIN=20
|
||||
CROSSCODE_NODE_WARN=22
|
||||
@@ -358,8 +358,8 @@ node_major() { node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo
|
||||
# 1.0–1.1 has no .gitignore for its ecosystem.config.cjs). Nor do the files in the folders this
|
||||
# script writes into (Accounts below 1.3.0 doesn't ignore the database dumps made before each
|
||||
# deploy, so the dump would stop the very deploy that brings the .gitignore).
|
||||
CROSSCODE_OWN_FILES=(apps/events/ecosystem.config.js apps/accounts/ecosystem.config.cjs)
|
||||
CROSSCODE_OWN_DIRS=(apps/accounts/backend/backups/)
|
||||
CROSSCODE_OWN_FILES=(apps/events/ecosystem.config.js apps/accounts/ecosystem.config.cjs apps/website/ecosystem.config.cjs)
|
||||
CROSSCODE_OWN_DIRS=(apps/accounts/backend/backups/ apps/website/backend/backups/)
|
||||
local_changes() {
|
||||
git_in "$1" status --porcelain --untracked-files=all |
|
||||
awk -v own="${CROSSCODE_OWN_FILES[*]}" -v dirs="${CROSSCODE_OWN_DIRS[*]}" '
|
||||
|
||||
+80
-45
@@ -1,7 +1,8 @@
|
||||
# shellcheck shell=bash
|
||||
# crosscode install: a new church on this server (from hope-events' scripts/install.sh 2.1.x;
|
||||
# behind frp from the Hub in agent 1.0, docs/AGENT-1.0-PLAN.md §7).
|
||||
# Events only so far; Accounts, Website and App follow as their products/*.sh are added.
|
||||
# A new church starts with Events or Accounts; the Website is added next to Accounts with
|
||||
# `crosscode add` (WEBSITE-1.0-PLAN §11). The App follows as its products/app.sh is added.
|
||||
|
||||
install_usage() {
|
||||
cat <<'EOF'
|
||||
@@ -160,6 +161,21 @@ cmd_install() {
|
||||
install_done "$church" "$product" "$pdomain" "$api" "$web" "$frp"
|
||||
}
|
||||
|
||||
# Where a product goes on the church's address: <product>.<address>, except the Website, which is
|
||||
# the church's own site: www.<address>, or the Cross Code address itself (hope.crosscode.co.za), as
|
||||
# the Hub does (Hub 2.21.0).
|
||||
default_domain() {
|
||||
local product="$1" address="$2"
|
||||
if [ "$product" = website ]; then
|
||||
case "$address" in
|
||||
*.crosscode.co.za) printf '%s' "$address" ;;
|
||||
*) printf 'www.%s' "$address" ;;
|
||||
esac
|
||||
else
|
||||
printf '%s.%s' "$product" "$address"
|
||||
fi
|
||||
}
|
||||
|
||||
# The checks every install and add share, before anything is touched.
|
||||
install_check_options() {
|
||||
local product="$1" ssl="$2" email="$3" version="$4" main="$5" frp="$6" api="$7" web="$8"
|
||||
@@ -197,6 +213,7 @@ install_product() {
|
||||
case "$product" in
|
||||
events) install_events "$@" ;;
|
||||
accounts) install_accounts "$@" ;;
|
||||
website) install_website "$@" ;;
|
||||
*) die "This version of crosscode can't install $product." ;;
|
||||
esac
|
||||
}
|
||||
@@ -224,7 +241,10 @@ install_done() {
|
||||
else
|
||||
info "DNS (if not set yet): $domain → this server (A record, or a CNAME)."
|
||||
fi
|
||||
info "Open https://$domain/setup to create the admin account."
|
||||
case "$product" in
|
||||
website) info "Open https://$domain/admin and sign in with the admin email the Hub was given: that account becomes the first Owner." ;;
|
||||
*) info "Open https://$domain/setup to create the admin account." ;;
|
||||
esac
|
||||
if [ "$product" = accounts ]; then info "Updates: crosscode deploy $church (Accounts is always updated first)"; else info "Updates: crosscode deploy $church $product"; fi
|
||||
}
|
||||
|
||||
@@ -232,11 +252,13 @@ add_usage() {
|
||||
cat <<'EOF'
|
||||
crosscode add <church> <product> [options]
|
||||
|
||||
Adds a product to a church already installed here (from phase 3: Accounts next to Events), in
|
||||
Adds a product to a church already installed here (Accounts next to Events, the Website next to
|
||||
Accounts), in
|
||||
its own folder, database, PM2 processes and site, run by the church's app user. If a step fails,
|
||||
what this run made is removed again; the church's other products aren't touched.
|
||||
|
||||
--domain <domain> where it's served (default: <product>.<the church's address>)
|
||||
--domain <domain> where it's served (default: <product>.<the church's address>; the
|
||||
Website: www.<address>, or the address itself on a Cross Code address)
|
||||
--version <product>@x.y.z that release (default: the latest)
|
||||
--main the latest main (staging churches only)
|
||||
--api-port <n> backend port (default: the first free one from 5000)
|
||||
@@ -276,15 +298,17 @@ cmd_add() {
|
||||
[ -n "$church" ] && [ -n "$product" ] || { add_usage; die "Name the church and the product."; }
|
||||
valid_slug "$church" || die "\"$church\" isn't a church name."
|
||||
is_known_product "$product" || die "Unknown product \"$product\"."
|
||||
[ "$product" = events ] || [ "$product" = accounts ] || die "This version of crosscode can only add events and accounts."
|
||||
case "$product" in events|accounts|website) ;; *) die "This version of crosscode can only add events, accounts and website." ;; esac
|
||||
install_check_options "$product" "$ssl" "$email" "$version" "$main" "$frp" "$api" "$web"
|
||||
require_root
|
||||
load_church "$church"
|
||||
! church_has_product "$product" || die "$church already has $product (crosscode status $church)."
|
||||
# The Website signs in through the church's Accounts and can't be reached without it (WEBSITE-1.0-PLAN §11).
|
||||
[ "$product" != website ] || church_has_product accounts || die "The Website needs the church's Accounts: add it first (crosscode add $church accounts)."
|
||||
local address user="" existing
|
||||
address="$(cenv ADDRESS)"
|
||||
[ -n "$domain" ] || [ -n "$address" ] || die "--domain is needed: the church has no address in church.env."
|
||||
domain="${domain:-$product.$address}"
|
||||
domain="${domain:-$(default_domain "$product" "$address")}"
|
||||
[[ "$domain" =~ ^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$ ]] || die "--domain: expected a domain."
|
||||
[ ! -e "$(church_dir "$church")/$product" ] || die "$(church_dir "$church")/$product exists already. Move it away first."
|
||||
# The church's app user: the one its other products run as.
|
||||
@@ -422,24 +446,34 @@ install_events() {
|
||||
die "The backend didn't answer with its version (sudo -u $user pm2 logs $name-backend)."
|
||||
}
|
||||
|
||||
install_accounts() {
|
||||
local church="$1" user="$2" domain="$3" api="$4" web="$5" version="$6" main="$7" ssl="$8" email="$9" frp="${10}"
|
||||
local dir app db pass name ref
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/accounts.sh"
|
||||
dir="$(church_dir "$church")/accounts"
|
||||
app="$dir/apps/accounts"
|
||||
db="$(printf '%s_accounts' "$church" | tr '-' '_')"
|
||||
name="$church-accounts"
|
||||
church_env_set ACCOUNTS_DIR "$dir"
|
||||
church_env_set ACCOUNTS_DOMAIN "$domain"
|
||||
church_env_set ACCOUNTS_PM2 "$name-backend $name-frontend"
|
||||
church_env_set ACCOUNTS_PORTS "$api $web"
|
||||
church_env_set ACCOUNTS_DB "$db"
|
||||
church_env_set ACCOUNTS_USER "$user"
|
||||
[ "$frp" = 0 ] || church_env_set ACCOUNTS_FRP 1
|
||||
install_accounts() { install_app accounts Accounts ACCOUNTS_SECRET "$@"; }
|
||||
install_website() { install_app website Website WEBSITE_SECRET "$@"; }
|
||||
|
||||
step "Accounts: code ($dir)"
|
||||
# install_app <product> <title> <generated secret> <church> <user> <domain> <api> <web> <version>
|
||||
# <main> <ssl> <email> <frp>: Accounts and the Website (and later the App), which share one shape:
|
||||
# a checkout of crosscode-platform, apps/<product>/{backend,frontend}, ecosystem.config.cjs, and
|
||||
# one secret generated here that never leaves the server.
|
||||
install_app() {
|
||||
local product="$1" title="$2" secret="$3"
|
||||
shift 3
|
||||
local church="$1" user="$2" domain="$3" api="$4" web="$5" version="$6" main="$7" ssl="$8" email="$9" frp="${10}"
|
||||
local dir app db pass name ref prefix
|
||||
# shellcheck source=/dev/null
|
||||
source "$CROSSCODE_HOME/products/$product.sh"
|
||||
prefix="$(printf '%s' "$product" | tr '[:lower:]' '[:upper:]')"
|
||||
dir="$(church_dir "$church")/$product"
|
||||
app="$dir/apps/$product"
|
||||
db="$(printf '%s_%s' "$church" "$product" | tr '-' '_')"
|
||||
name="$church-$product"
|
||||
church_env_set "${prefix}_DIR" "$dir"
|
||||
church_env_set "${prefix}_DOMAIN" "$domain"
|
||||
church_env_set "${prefix}_PM2" "$name-backend $name-frontend"
|
||||
church_env_set "${prefix}_PORTS" "$api $web"
|
||||
church_env_set "${prefix}_DB" "$db"
|
||||
church_env_set "${prefix}_USER" "$user"
|
||||
[ "$frp" = 0 ] || church_env_set "${prefix}_FRP" 1
|
||||
|
||||
step "$title: code ($dir)"
|
||||
mkdir -p "$dir"
|
||||
undo_add dir "$dir"
|
||||
chown "$user:$user" "$dir"
|
||||
@@ -448,63 +482,64 @@ install_accounts() {
|
||||
if [ "$main" = 1 ]; then
|
||||
version=origin/main
|
||||
elif [ -z "$version" ]; then
|
||||
version="$(latest_tag "$dir" accounts)"
|
||||
[ -n "$version" ] || die "No accounts@x.y.z release tags yet (use --version or --main)."
|
||||
version="$(latest_tag "$dir" "$product")"
|
||||
[ -n "$version" ] || die "No $product@x.y.z release tags yet (use --version or --main)."
|
||||
fi
|
||||
run_as "$user" "$dir" git checkout -q --detach "$version"
|
||||
ref="$(checkout_ref "$dir" accounts)"
|
||||
ref="$(checkout_ref "$dir" "$product")"
|
||||
info "At $ref"
|
||||
report_result_json versions "{\"accounts\":\"$ref\"}"
|
||||
report_result_json versions "{\"$product\":\"$ref\"}"
|
||||
|
||||
step "Accounts: database ($db on $(db_host))"
|
||||
step "$title: database ($db on $(db_host))"
|
||||
! db_exists "$db" || die "A database or role named $db already exists on $(db_host). Remove it first if it's left over, or choose another church name."
|
||||
pass="$(random_secret 32)"
|
||||
undo_add db "$db"
|
||||
db_create "$db" "$pass"
|
||||
|
||||
step "Accounts: configuration"
|
||||
step "$title: configuration"
|
||||
local trust=1
|
||||
[ "$frp" = 0 ] || trust=loopback
|
||||
(
|
||||
export CROSSCODE_GEN_NODE_ENV=production
|
||||
export CROSSCODE_GEN_ACCOUNTS_SECRET
|
||||
CROSSCODE_GEN_ACCOUNTS_SECRET="$(random_secret 64)"
|
||||
local generated
|
||||
generated="$(random_secret 64)"
|
||||
export "CROSSCODE_GEN_$secret=$generated"
|
||||
export CROSSCODE_GEN_DATABASE_URL="postgresql://$db:$pass@$(db_host):$(db_port)/$db"
|
||||
env_apply "$app" accounts "$ref" --var "domain=$domain" --var "apiPort=$api" --var "webPort=$web" --var "church=$church" \
|
||||
env_apply "$app" "$product" "$ref" --var "domain=$domain" --var "apiPort=$api" --var "webPort=$web" --var "church=$church" \
|
||||
--fallback "TRUST_PROXY=$trust"
|
||||
) | sed 's/^/ /'
|
||||
[ "${PIPESTATUS[0]}" = 0 ] || die "The .env files couldn't be written (see above)."
|
||||
chown "$user:$user" "$app/backend/.env" "$app/frontend/.env.production"
|
||||
chmod 600 "$app/backend/.env" "$app/frontend/.env.production"
|
||||
accounts_ensure_pm2_config "$dir" "$user"
|
||||
"${product}_ensure_pm2_config" "$dir" "$user"
|
||||
|
||||
step "Accounts: install, migrate, build"
|
||||
accounts_install_deps "$dir" "$user"
|
||||
accounts_migrate "$dir" "$user"
|
||||
accounts_build "$dir" "$user"
|
||||
step "$title: install, migrate, build"
|
||||
"${product}_install_deps" "$dir" "$user"
|
||||
"${product}_migrate" "$dir" "$user"
|
||||
"${product}_build" "$dir" "$user"
|
||||
|
||||
step "Accounts: PM2"
|
||||
step "$title: PM2"
|
||||
undo_add pm2 "$user" "$name-backend $name-frontend"
|
||||
run_as "$user" "$app" pm2 startOrReload ecosystem.config.cjs
|
||||
run_as "$user" "$app" pm2 save
|
||||
|
||||
if [ "$frp" = 1 ]; then
|
||||
step "Accounts: frpc tunnels"
|
||||
frpc_add "$church" accounts "$web" "$api"
|
||||
undo_add frpc "$church" accounts
|
||||
step "$title: frpc tunnels"
|
||||
frpc_add "$church" "$product" "$web" "$api"
|
||||
undo_add frpc "$church" "$product"
|
||||
frpc_reload
|
||||
else
|
||||
step "Accounts: nginx ($domain)"
|
||||
step "$title: nginx ($domain)"
|
||||
install_site_nginx "$name" "$domain" "$api" "$web"
|
||||
undo_add nginx "$name"
|
||||
if [ "$ssl" = 1 ]; then
|
||||
step "Accounts: certificate"
|
||||
step "$title: certificate"
|
||||
certbot --nginx -d "$domain" --non-interactive --agree-tos -m "$email" --redirect
|
||||
fi
|
||||
fi
|
||||
|
||||
step "Accounts: checking it answers"
|
||||
wait_for_version "$(accounts_health_url)" "$(accounts_expected_version "$dir")" 90 ||
|
||||
step "$title: checking it answers"
|
||||
wait_for_version "$("${product}_health_url")" "$("${product}_expected_version" "$dir")" 90 ||
|
||||
die "The backend didn't answer with its version (sudo -u $user pm2 logs $name-backend)."
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"schema": "crosscode.env-template/1",
|
||||
"product": "website",
|
||||
"files": {
|
||||
"backend/.env": [
|
||||
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
|
||||
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
|
||||
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
|
||||
{ "name": "WEBSITE_SECRET", "layer": "generated", "required": true, "description": "Signs preview links and cookies, encrypts stored secrets: never change it" },
|
||||
{ "name": "WEBSITE_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address (www. or the Cross Code address)" },
|
||||
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
|
||||
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg" },
|
||||
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
|
||||
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
|
||||
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCW-…)" },
|
||||
{ "name": "HUB_ADMIN_NAME", "layer": "install" },
|
||||
{ "name": "HUB_ADMIN_EMAIL", "layer": "install", "description": "The first person to sign in with this address (through Accounts, verified) becomes the Owner" },
|
||||
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
# shellcheck shell=bash
|
||||
# The Church Website's hooks for the crosscode script (docs/WEBSITE-1.0-PLAN.md §11), the same
|
||||
# hooks as products/accounts.sh. Every hook takes the product's checkout (WEBSITE_DIR, a checkout of
|
||||
# crosscode-platform) and the app user. Values come from church.env (CENV): WEBSITE_DIR,
|
||||
# WEBSITE_DOMAIN, WEBSITE_PM2 ("<backend> <frontend>"), WEBSITE_PORTS ("<api> <web>"),
|
||||
# WEBSITE_DB, WEBSITE_USER.
|
||||
|
||||
website_app() { printf '%s/apps/website' "$1"; }
|
||||
|
||||
website_pm2_names() { pvar website PM2; }
|
||||
|
||||
website_api_port() { local p; read -r p _ <<< "$(pvar website PORTS)"; printf '%s' "${p:-5300}"; }
|
||||
website_web_port() { local p; read -r _ p <<< "$(pvar website PORTS)"; printf '%s' "${p:-3300}"; }
|
||||
website_health_url() { printf 'http://127.0.0.1:%s/api/health' "$(website_api_port)"; }
|
||||
|
||||
website_expected_version() {
|
||||
node -p 'require(process.argv[1]).version' "$(website_app "$1")/backend/package.json"
|
||||
}
|
||||
|
||||
# The shared packages the Website is built with (contracts, auth-client for signing in, ui for its pages).
|
||||
website_shared_packages() {
|
||||
local p
|
||||
for p in packages/contracts packages/ui packages/auth-client; do
|
||||
[ -f "$1/$p/package.json" ] && printf '%s\n' "$p"
|
||||
done
|
||||
}
|
||||
|
||||
# A database dump into backend/backups/ (the last 14 are kept), before every deploy and uninstall.
|
||||
website_backup() {
|
||||
local dir="$1" user="$2" backend
|
||||
backend="$(website_app "$dir")/backend"
|
||||
# shellcheck disable=SC2016 # the app user's shell expands these
|
||||
run_as "$user" "$backend" bash -c '
|
||||
set -euo pipefail
|
||||
url="$(grep -E "^DATABASE_URL=" .env | head -1 | cut -d= -f2- | sed -e "s/^\"//" -e "s/\"$//")"
|
||||
mkdir -p backups
|
||||
file="backups/website-$(date +%Y%m%d-%H%M%S).sql.gz"
|
||||
pg_dump --no-owner --no-privileges "$url" | gzip > "$file"
|
||||
chmod 600 "$file"
|
||||
ls -1t backups/website-*.sql.gz | tail -n +15 | xargs -r rm -f
|
||||
echo " $file"'
|
||||
}
|
||||
|
||||
website_install_deps() {
|
||||
local -a ws=()
|
||||
local p
|
||||
while IFS= read -r p; do ws+=(-w "$p"); done < <(website_shared_packages "$1")
|
||||
run_as "$2" "$1" npm ci --include=dev --no-audit --no-fund --include-workspace-root "${ws[@]}" -w apps/website/backend -w apps/website/frontend
|
||||
}
|
||||
|
||||
website_migrate() {
|
||||
run_as "$2" "$(website_app "$1")/backend" npm run prisma:deploy
|
||||
}
|
||||
|
||||
website_build() {
|
||||
local p
|
||||
for p in packages/contracts packages/auth-client; do
|
||||
[ ! -f "$1/$p/package.json" ] || run_as "$2" "$1/$p" npm run build || return 1
|
||||
done
|
||||
run_as "$2" "$(website_app "$1")/backend" npm run build &&
|
||||
run_as "$2" "$(website_app "$1")/frontend" npm run build
|
||||
}
|
||||
|
||||
website_rollback_build() {
|
||||
website_install_deps "$1" "$2" && website_build "$1" "$2"
|
||||
}
|
||||
|
||||
# The install's own PM2 config (not in git), made from the example the first time.
|
||||
website_ensure_pm2_config() {
|
||||
local dir="$1" user="$2" app conf backend frontend
|
||||
app="$(website_app "$dir")"
|
||||
conf="$app/ecosystem.config.cjs"
|
||||
[ -f "$conf" ] && return 0
|
||||
read -r backend frontend <<< "$(website_pm2_names)"
|
||||
sed -e "s/'website-backend'/'${backend}'/" \
|
||||
-e "s/'website-frontend'/'${frontend}'/" \
|
||||
-e "s/-p 3300/-p $(website_web_port)/" \
|
||||
"$app/ecosystem.config.example.cjs" > "$conf"
|
||||
chown "$user:$user" "$conf" 2>/dev/null || true
|
||||
info "Created $conf from the example."
|
||||
}
|
||||
|
||||
website_reload() {
|
||||
website_ensure_pm2_config "$1" "$2"
|
||||
run_as "$2" "$(website_app "$1")" pm2 reload ecosystem.config.cjs --update-env
|
||||
}
|
||||
|
||||
# export.json (crosscode.church-export/1 with its `website` part: pages, messages, events, media,
|
||||
# the editors; no secrets) into <out dir>. The uploads are copied by website_copy_uploads.
|
||||
website_export() {
|
||||
local app
|
||||
app="$(website_app "$1")"
|
||||
run_as "$2" "$app/backend" npx tsx scripts/export-church.ts --out-dir "$3"
|
||||
}
|
||||
|
||||
# The church's uploads (photos, documents) into <out dir>, as Events' copy_uploads.
|
||||
website_copy_uploads() {
|
||||
local uploads
|
||||
uploads="$(website_app "$1")/backend/uploads"
|
||||
mkdir -p "$2"
|
||||
[ ! -d "$uploads" ] || rsync -a "$uploads/" "$2/"
|
||||
}
|
||||
|
||||
# What uninstall keeps for 30 days: the backups and the .env (its WEBSITE_SECRET decrypts what's stored).
|
||||
website_keep() {
|
||||
local app dest="$2"
|
||||
app="$(website_app "$1")"
|
||||
mkdir -p "$dest"
|
||||
[ ! -d "$app/backend/backups" ] || rsync -a "$app/backend/backups/" "$dest/backups/"
|
||||
cp -p "$app/backend/.env" "$dest/backend.env" 2>/dev/null || true
|
||||
chmod -R go-rwx "$dest"
|
||||
}
|
||||
|
||||
website_env_vars() {
|
||||
printf '%s\n' --var "domain=$(pvar website DOMAIN)" --var "apiPort=$(website_api_port)" --var "webPort=$(website_web_port)" --var "church=$(cenv CHURCH)"
|
||||
}
|
||||
|
||||
# As events_resolve_failed_migrations: a migration that failed in this release and isn't in the
|
||||
# previous one is marked as rolled back (the backup taken first has the database as it was).
|
||||
website_resolve_failed_migrations() {
|
||||
local dir="$1" user="$2" prev="$3" backend name
|
||||
backend="$(website_app "$dir")/backend"
|
||||
local -a failed
|
||||
# shellcheck disable=SC2016 # SQL through psql, run as the app user
|
||||
mapfile -t failed < <(run_as "$user" "$backend" bash -c '
|
||||
url="$(grep -E "^DATABASE_URL=" .env | head -1 | cut -d= -f2- | sed -e "s/^\"//" -e "s/\"$//")"
|
||||
psql "$url" -At -c "select migration_name from _prisma_migrations where finished_at is null and rolled_back_at is null"')
|
||||
for name in "${failed[@]}"; do
|
||||
[ -n "$name" ] || continue
|
||||
if git_in "$dir" cat-file -e "$prev:apps/website/backend/prisma/migrations/$name/migration.sql" 2>/dev/null; then
|
||||
warn "website: $name failed but $prev has it too; left for a look (npx prisma migrate status)."
|
||||
continue
|
||||
fi
|
||||
run_as "$user" "$backend" npx prisma migrate resolve --rolled-back "$name" >/dev/null
|
||||
info "website: marked the failed migration $name as rolled back."
|
||||
report_result "resolvedMigration" "$name"
|
||||
done
|
||||
}
|
||||
@@ -105,9 +105,13 @@ setup() {
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"Name the church and the product"* ]]
|
||||
|
||||
run bash "$CC" add hope website --no-ssl
|
||||
run bash "$CC" add hope app --no-ssl
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"can only add events and accounts"* ]]
|
||||
[[ "$output" == *"can only add events, accounts and website"* ]]
|
||||
|
||||
run bash "$CC" add hope website
|
||||
[ "$status" -eq 1 ]
|
||||
[[ "$output" == *"--email is required"* ]]
|
||||
|
||||
run bash "$CC" add hope accounts
|
||||
[ "$status" -eq 1 ]
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env bats
|
||||
# The Church Website's hooks that don't need a server (WEBSITE-1.0-PLAN §11), and where `crosscode
|
||||
# add` puts it on the church's address. Run with `npm run test:scripts`.
|
||||
|
||||
setup() {
|
||||
# shellcheck source=../lib/common.sh
|
||||
source "$BATS_TEST_DIRNAME/../lib/common.sh"
|
||||
# shellcheck source=../lib/install.sh
|
||||
source "$BATS_TEST_DIRNAME/../lib/install.sh"
|
||||
# shellcheck source=../products/website.sh
|
||||
source "$BATS_TEST_DIRNAME/../products/website.sh"
|
||||
TMP="$BATS_TEST_TMPDIR"
|
||||
CALLS="$TMP/calls"
|
||||
: > "$CALLS"
|
||||
# Record what would run, as the app user, instead of running it.
|
||||
run_as() { local user="$1" dir="$2"; shift 2; echo "$user|${dir#"$TMP"/}|$*" >> "$CALLS"; }
|
||||
CENV=()
|
||||
}
|
||||
|
||||
checkout() {
|
||||
local dir="$TMP/$1" p
|
||||
for p in contracts ui auth-client; do
|
||||
mkdir -p "$dir/packages/$p"
|
||||
echo "{\"name\":\"@crosscode/$p\"}" > "$dir/packages/$p/package.json"
|
||||
done
|
||||
mkdir -p "$dir/apps/website/backend" "$dir/apps/website/frontend"
|
||||
echo '{"version":"1.0.0"}' > "$dir/apps/website/backend/package.json"
|
||||
cp "$BATS_TEST_DIRNAME/../../apps/website/ecosystem.config.example.cjs" "$dir/apps/website/"
|
||||
}
|
||||
|
||||
@test "the Website goes on www., or on the Cross Code address itself; other products on <product>." {
|
||||
[ "$(default_domain website hopefamily.co.za)" = www.hopefamily.co.za ]
|
||||
[ "$(default_domain website hope.crosscode.co.za)" = hope.crosscode.co.za ]
|
||||
[ "$(default_domain events hopefamily.co.za)" = events.hopefamily.co.za ]
|
||||
[ "$(default_domain accounts hope.crosscode.co.za)" = accounts.hope.crosscode.co.za ]
|
||||
}
|
||||
|
||||
@test "the Website is a product this script deploys" {
|
||||
is_supported_product website
|
||||
}
|
||||
|
||||
@test "contracts, ui and auth-client are installed; contracts and auth-client built before the Website" {
|
||||
checkout new
|
||||
website_install_deps "$TMP/new" hope
|
||||
grep -qx 'hope|new|npm ci --include=dev --no-audit --no-fund --include-workspace-root -w packages/contracts -w packages/ui -w packages/auth-client -w apps/website/backend -w apps/website/frontend' "$CALLS"
|
||||
: > "$CALLS"
|
||||
website_build "$TMP/new" hope
|
||||
[ "$(cut -d'|' -f2 "$CALLS" | tr '\n' ' ')" = "new/packages/contracts new/packages/auth-client new/apps/website/backend new/apps/website/frontend " ]
|
||||
}
|
||||
|
||||
@test "ports default to 5300 / 3300, else church.env's" {
|
||||
[ "$(website_api_port)" = 5300 ]
|
||||
[ "$(website_web_port)" = 3300 ]
|
||||
church_env_set WEBSITE_PORTS "5410 3410"
|
||||
[ "$(website_health_url)" = http://127.0.0.1:5410/api/health ]
|
||||
[ "$(website_web_port)" = 3410 ]
|
||||
}
|
||||
|
||||
@test "the PM2 config is made once, with the church's names and port" {
|
||||
checkout new
|
||||
church_env_set WEBSITE_PM2 "hope-website-backend hope-website-frontend"
|
||||
church_env_set WEBSITE_PORTS "5410 3410"
|
||||
info() { :; }
|
||||
website_ensure_pm2_config "$TMP/new" "$(id -un)"
|
||||
conf="$TMP/new/apps/website/ecosystem.config.cjs"
|
||||
grep -q "'hope-website-backend'" "$conf"
|
||||
grep -q "'hope-website-frontend'" "$conf"
|
||||
grep -q -- "-p 3410" "$conf"
|
||||
echo changed > "$conf"
|
||||
website_ensure_pm2_config "$TMP/new" "$(id -un)"
|
||||
[ "$(cat "$conf")" = changed ]
|
||||
}
|
||||
|
||||
@test "the uploads are copied into the export; none is fine" {
|
||||
command -v rsync >/dev/null || skip "rsync isn't installed here"
|
||||
checkout new
|
||||
website_copy_uploads "$TMP/new" "$TMP/out1"
|
||||
[ -d "$TMP/out1" ]
|
||||
mkdir -p "$TMP/new/apps/website/backend/uploads/2026"
|
||||
echo jpg > "$TMP/new/apps/website/backend/uploads/2026/hero.jpg"
|
||||
website_copy_uploads "$TMP/new" "$TMP/out2"
|
||||
[ "$(cat "$TMP/out2/2026/hero.jpg")" = jpg ]
|
||||
}
|
||||
Reference in New Issue
Block a user