Compare commits

...
Author SHA1 Message Date
joshua 58cadbf472 Merge branch 'fix/link-after-install' 2026-11-26 16:14:20 +02:00
joshuaandClaude Opus 5.5 f6a536ad64 Accounts 1.7.1, Website 1.0.2, Events 3.7.1: link right after an install; Preview behind the proxy
Found installing the Website for cross-demo2.

- All three: a connect involving an install that isn't in the cached copy
  of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at
  most once a minute) instead of refusing. A new Website's admin couldn't
  sign in for up to 30 minutes.
- Accounts: a heartbeat on every start.
- Website: /admin links to Accounts on the spot (at most every 15 s), one
  connect to Accounts at a time, and the problem page says "not linked
  yet" (ACCOUNTS_NOT_LINKED). Preview redirected to the server's own
  http://localhost:<web port>: the preview routes now answer with a
  relative Location.
- Events: a new Website can connect for the event feed straight away.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:14:20 +02:00
joshua 05d808b74c Merge branch 'docs/hub-2.23.1' 2026-11-26 15:27:27 +02:00
joshuaandClaude Opus 5.5 20a23a3ba8 docs: Hub 2.23.1 deployed (Accounts version from the heartbeat)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:27:26 +02:00
joshua 9c9c96dd2c Merge branch 'docs/hub-2.23.0' 2026-11-26 15:11:58 +02:00
joshuaandClaude Opus 5.5 f73761f956 docs: Hub 2.23.0 deployed (requirements carry forward)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:11:57 +02:00
joshua 62441ad437 Merge branch 'docs/site-1.7.0' 2026-11-26 14:38:00 +02:00
joshuaandClaude Opus 5.5 7814a64cf7 docs: crosscode-site 1.7.0 released (the Website on sale)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:37:59 +02:00
joshua 679f61febf Merge branch 'fix/website-1.0.1' 2026-11-26 14:36:35 +02:00
joshuaandClaude Opus 5.5 723bb15a5e website 1.0.1: thumbnails from the site, Calendar dates
- The messages' YouTube thumbnails are served from the site
  (/api/thumbnails/<id>.jpg): the backend fetches a message's thumbnail
  once and keeps it in uploads/.thumbnails (only the site's own videos,
  only a JPEG), so visitors ask nothing of YouTube before pressing play.
  The messages page preloads the first one (its LCP: Heritage 89 -> 95).
- Calendar events' dates read "Sun · November", not
  "Sun (month: November)".
- e2e: no request to YouTube or Spotify before play; the variant
  screenshots round section heights to whole pixels (a one-pixel flake);
  the e2e thumbnail is one of the demo's illustrations.
- crosscode script: a Website's export leaves out uploads/.thumbnails.
- docs: release checks on 1.0.1, VERSIONS, handover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:36:34 +02:00
joshua dd0e5e17b3 Merge branch 'docs/website-release-checks' 2026-11-26 12:03:10 +02:00
joshuaandClaude Opus 5.5 7216035e49 docs: website release checks run again on the release build
Variants: axe passes everywhere, all 104 baselines taken (67 new to look
through). Lighthouse 11 of 12 (Heritage messages 89, the YouTube
thumbnail as LCP). Found: Calendar dates print "Sun (month: November)".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:03:10 +02:00
joshua 9bf1739734 Merge branch 'feat/website-release-checks' 2026-11-26 10:54:44 +02:00
joshuaandClaude Opus 5.5 0b99686ca7 website 1.0.0: release checks, contrast and map fixes
- e2e: every section variant in every template (axe and 312 screenshots
  compared with local baselines), Lighthouse on a phone (median of three,
  CPU slowdown calibrated to the machine), the whole suite on real Postgres
  with E2E_DATABASE_URL, a frozen clock, E2E_REUSE for running servers.
- Fixes found by them: contrast on Bold's service times panel and Calendar
  event dates; the OpenStreetMap embed loads only once on screen; the
  messages page's first thumbnail is eager, its host preconnected.
- The restore e2e waits for its second publish (raced on Postgres).
- docs: Hub 2.22.0 deployed; website@1.0.0 released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:54:43 +02:00
joshua 6ffad24db1 Merge branch 'docs/handover-tidy' 2026-11-25 16:29:08 +02:00
joshuaandClaude Opus 5.5 268c9cde88 docs: handover typo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:29:07 +02:00
joshua 9086b549a8 Merge branch 'docs/release-contracts-1.18-hub-2.22' 2026-11-25 16:28:43 +02:00
joshuaandClaude Opus 5.5 154bb94da7 docs: contracts 1.18.0 and Hub 2.22.0 released; Website status
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:28:42 +02:00
joshua 312c32c6cb Merge branch 'feat/storage-request' 2026-11-25 16:18:48 +02:00
joshuaandClaude Opus 5.5 283e75737d contracts 1.18.0 + website: Get more storage
contracts: hub.storageRequestSchema and its reply, a sample and JSON
Schemas. Website: an Owner or Admin asks for more 5 GB steps under
Media library (signed to the Hub); the heartbeat reports the licence's
storage limit, so the Hub emails the church at 80% and when full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:18:46 +02:00
joshua 53e5de3f14 Merge branch 'feat/website-settings-seo' 2026-11-25 15:30:29 +02:00
joshuaandClaude Opus 5.5 085265392e feat(website): church details, settings, audit log, search engine data, safer editing
Church details saved through Accounts' church.update (live at once).
Settings: Search Console and Bing codes, Coming soon line, menu order.
Audit log and recent edits. A made share image, Event / VideoObject /
PodcastEpisode / BreadcrumbList structured data, permanent redirects
from old page addresses. Saves refused when someone else saved in
between; Ministry leaders' events; templates previewed with the
church's own content before choosing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:30:27 +02:00
joshua d8ed238042 Merge branch 'feat/website-event-feed' 2026-11-25 14:37:43 +02:00
joshuaandClaude Opus 5.5 b767b45e64 feat(website): the event feed both ways, and Linked products
Publish my events: the Website's simple events as crosscode.event/1
(GET /api/feed/v1/events, updatedSince, removals in deleted for 90
days) and a signed event.changed to linked siblings. Show events
from: each sibling's feed every 15 minutes and at once on its signed
event.changed; read-only copies of only that sibling's events, one
bad event skipped, the last good copy kept. Admin: Linked products.
church.changed from Accounts refreshes the profile at once. Plan:
the video hero, more blocks and more pages move to website@1.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:37:42 +02:00
joshua 193a338ed2 Merge branch 'feat/website-image-sizes' 2026-11-25 14:04:44 +02:00
joshuaandClaude Opus 5.5 2ba755145d feat(website): photos upright, without metadata, in responsive sizes
Every upload is turned upright, stripped of its metadata (EXIF, GPS),
kept at most 2400 px wide and saved at 480/960/1600 px in WebP and
JPEG; the pages pick the size with <picture> and srcset. Every file
counts towards storage; a photo that can't be read is refused. sharp
0.35 (prebuilt, no build step on the servers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:04:43 +02:00
joshua 6be1a2782d Merge branch 'feat/website-people-messages-events' 2026-11-25 13:05:35 +02:00
joshuaandClaude Opus 5.5 37a1f6acf1 feat(website): people and roles, messages with the YouTube feed, simple events
People: Owners and Admins add someone by email (people.ensure through
Accounts), change roles, remove access; only Owners touch Owners,
nobody changes themselves, a lower role ends sessions at once.
Messages: from a YouTube channel or playlist every hour (public feed,
no key) or by hand with a YouTube or Spotify link; own publish, hide.
Simple events: own publish, cancel, remove. Tests and e2e with axe on
the new screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:05:33 +02:00
joshua 9b8f10e3c8 Merge branch 'feat/website-admin' 2026-11-25 12:30:29 +02:00
111 changed files with 5718 additions and 205 deletions
+33
View File
@@ -2,6 +2,39 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## accounts@1.7.1 + website@1.0.2 + events@3.7.1 - 2026-11-26
Found installing the Website for cross-demo2. Details in each app's CHANGELOG.md. No migrations.
- **Linking right after an install** (all three): a connect involving an install that isn't in the
cached copy of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at most once a
minute) instead of refusing. Before, a new product and its siblings only learned of each other at
their 15-minute heartbeats, so a new Website's admin couldn't sign in for up to 30 minutes.
- **Accounts 1.7.1:** also a heartbeat on every start.
- **Website 1.0.2:** opening `/admin` without a link to Accounts links on the spot; the problem page
says "not linked yet" (`ACCOUNTS_NOT_LINKED`) instead of "can't reach your sign-in". Preview no
longer redirects to the server's own `http://localhost:<web port>` (relative redirects).
- **Events 3.7.1:** a new Website can connect for the event feed straight away.
## website@1.0.1 + crosscode script - 2026-11-26
Details in `apps/website/CHANGELOG.md`.
- **Website 1.0.1:** the messages' YouTube thumbnails are served from the site
(`/api/thumbnails/<id>.jpg`), so visitors ask nothing of YouTube until they press play; the
Calendar events' dates read "Sun · November", not "Sun (month: November)". No migration.
- **crosscode script:** a Website's export leaves out `uploads/.thumbnails` (the kept thumbnails).
## contracts@1.18.0 - 2026-11-25
"Get more storage" for the Church Website (WEBSITE-1.0-PLAN §10, decision 12), with Hub 2.22.0.
Additive: products on 1.17.0 keep working.
- **`hub.storageRequestSchema` / `storageRequestResponseSchema`**: a Website asks the Hub for more
5 GB steps (`POST /api/installs/storage-request`, signed as the heartbeat), with what it uses,
its limit and who asked. `hub.STORAGE_STEP_BYTES`. New sample `hub-storage-request.json` and
JSON Schemas `hub-storage-request`, `hub-storage-request-response`.
## 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).
+16
View File
@@ -1,5 +1,21 @@
# Changelog — Accounts
## [1.7.1] - 2026-11-26
No migrations, no new settings.
### Fixed
- **A product installed after Accounts' last heartbeat links straight away.** Accounts accepted a
connect only from installs in its cached copy of the Hub's list, which it refreshed every 15
minutes. A new Church Website (or Events) was refused ("doesn't know that install yet") and tried
again only at its own next heartbeat, so its admin couldn't sign in for up to 30 minutes after the
install (found on cross-demo2). Now, for an install it doesn't know, Accounts sends the Hub a
heartbeat to get a fresh list and looks again (at most one such heartbeat a minute, so unknown
installs can't make it call the Hub more often). The same applies when an Accounts admin connects.
- **A heartbeat on every start**, not only the first: after a restart the list of the church's
products is fresh at once.
## [1.7.0] - 2026-11-24
Needs contracts 1.17.0. The first part of the Church Website 1.0.0 (WEBSITE-1.0-PLAN §11).
+5
View File
@@ -3,6 +3,11 @@
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).
## 1.7.1
- **New sites connect to your sign-in straight away.** A Church Website or Cross Events installed
for your church can be signed in to within moments, instead of after up to half an hour.
## 1.7.0
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-backend",
"version": "1.7.0",
"version": "1.7.1",
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
"private": true,
"type": "module",
+3 -1
View File
@@ -23,8 +23,10 @@ async function main() {
const server = app.listen(config.port, () => console.log(`[accounts] Listening on ${config.port} (${config.publicUrl}).`));
const stopJobs = await startJobs(ctx, url);
// 1.7.1: a heartbeat on every start, not only the first (as the Website), so the list of the
// church's products is fresh after a restart.
connectFromEnv(ctx).then((r) => {
if (r.connected) heartbeat(ctx).catch(() => {});
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
}).catch(() => {});
const stop = async () => {
+28 -4
View File
@@ -11,6 +11,7 @@ import {
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import { heartbeat } from '../hub/client.js';
import { audit, clientIp } from '../lib/audit.js';
import { callSibling, LinkCallError, siblingUrl } from './http.js';
import { keyPair, listedProduct } from './store.js';
@@ -24,6 +25,29 @@ export class LinkError extends Error {
/** Products that sign people in through Accounts. */
const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after Accounts' last heartbeat), Accounts asks the Hub for a fresh list with a heartbeat and looks
* again, so a new Website links straight away instead of up to 30 minutes later. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make Accounts call the Hub
* more often than that.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
r = { at: now, run: heartbeat(ctx).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
return listedProduct(ctx, installId);
}
async function self(ctx: Ctx) {
const installId = await ctx.settings.get('hub_install_id');
@@ -55,8 +79,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
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) });
export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) {
const sibling = await listedProduct(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
const sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -86,9 +110,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
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);
const sibling = await listedOrRefreshed(ctx, m.from.installId);
if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) {
throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
throw new LinkError('The Hub doesn\'t list that install for this church (Accounts asks it again at most once a minute).', '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);
@@ -2,6 +2,8 @@
// signed back-channel calls, deletion with a product that says "not yet", "download my data", the
// church profile, Connect, and admin and setup rules.
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { after, before, beforeEach, describe, test } from 'node:test';
import { churchSchema, IDENTITY_SCHEMA, LINK_SCHEMA, OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { generateEd25519, ed25519PublicToPem, newLinkNonce, newLinkSecret, signLink } from '@crosscode/contracts/signing';
@@ -156,6 +158,44 @@ describe('Connect from a product', () => {
const client = await h.provider.Client.find(APP_ID);
assert.deepEqual(client?.redirectUris, ['http://127.0.0.1:7/api/auth/callback']);
});
test('1.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const own = await startHarness({ now: () => clock });
const appKey = generateEd25519();
const NEW_ID = '5c1d7e2f-8a3b-4c4d-9e5f-6a7b8c9d0e1f';
const listed = { product: 'website', installId: NEW_ID, url: 'http://127.0.0.1:7', publicKey: ed25519PublicToPem(appKey.publicKey) };
// A Hub whose list has the new Website; Accounts' cached list doesn't yet.
const hubCalls: string[] = [];
const hub = http.createServer((req, res) => {
hubCalls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: [listed] }));
});
await new Promise<void>((r) => hub.listen(0, '127.0.0.1', () => r()));
try {
own.ctx.config.hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`;
await own.ctx.settings.setMany({ hub_install_secret: 'secret', hub_linked_products: '[]' });
const msg = (installId: string) => signLink({ schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'website', installId, url: 'http://127.0.0.1:7' }, to: { installId: ACCOUNTS_ID }, secret: newLinkSecret(), issuedAt: clock.toISOString(), nonce: newLinkNonce() }, appKey.privateKeyPem);
const send = (installId: string) => fetch(`${own.publicUrl}/api/links/v1/connect`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(msg(installId)) });
assert.equal((await send(NEW_ID)).status, 200, 'linked at once');
assert.deepEqual(hubCalls, ['/api/installs/heartbeat']);
assert.equal(await own.db.productLink.count({ where: { installId: NEW_ID } }), 1);
// An install the Hub doesn't list: refused, and within the minute the Hub isn't asked again.
const UNKNOWN = '7e3f9a4b-0c5d-4e6f-8a7b-9c0d1e2f3a4b';
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 1);
clock = new Date(clock.getTime() + 61_000);
assert.equal((await send(UNKNOWN)).status, 403);
assert.equal(hubCalls.length, 2);
} finally {
await new Promise((r) => hub.close(r));
await own.close();
}
});
});
describe('admin and setup', () => {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/accounts-frontend",
"version": "1.7.0",
"version": "1.7.1",
"private": true,
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
"scripts": {
+13
View File
@@ -5,6 +5,19 @@ 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.1] - 2026-11-26
No migrations, no new settings.
### Fixed
- **A product installed after this site's last heartbeat can connect straight away.** A connect
(in either direction) was refused while the other install wasn't in the cached copy of the Hub's
list, refreshed every 15 minutes. So a new Church Website couldn't connect for the event feed
until then. Now, for an install it doesn't know, the site sends the Hub a heartbeat to get a fresh
list and looks again (at most one such heartbeat a minute, so unknown installs can't make it call
the Hub more often). Same change as Accounts 1.7.1 and Website 1.0.2.
## [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**
+5
View File
@@ -12,6 +12,11 @@ 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.1
- **Connecting to your new Church Website works straight away**, so its events page can show your
Cross Events events as soon as it's installed, instead of after up to 15 minutes.
## 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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.7.0",
"version": "3.7.1",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+32 -4
View File
@@ -35,6 +35,34 @@ export class LinkError extends Error {
}
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
let refresh: { at: number; run: Promise<unknown> } | null = null;
/** For tests. */
export function forgetRefresh(): void {
refresh = null;
}
/**
* 3.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat, like a new Church Website), the site asks the Hub for a fresh
* list with a heartbeat and looks again, instead of refusing for up to 15 minutes. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make this site call the
* Hub more often than that.
*/
async function listedOrRefreshed(installId: string, now: Date) {
const found = await listedProduct(installId);
if (found) return found;
if (!refresh || now.getTime() - refresh.at >= REFRESH_EVERY_MS) {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS, and hub/client.js needs this module's siblings
const run = Promise.resolve().then(() => require('../hub/client').heartbeat())
.catch((e: Error) => console.warn('[links] Asking the Hub for a fresh list failed:', e?.message || e));
refresh = { at: now.getTime(), run };
}
await refresh.run;
return listedProduct(installId);
}
type Self = { installId: string; url: string; privateKeyPem: string };
@@ -81,8 +109,8 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) {
const sibling = await listedProduct(installId);
if (!sibling) 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 sibling = await listedOrRefreshed(installId, now);
if (!sibling) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self();
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -123,9 +151,9 @@ export async function acceptConnect(body: unknown, ip: string | null, now = new
const m = parsed.data;
const me = await self();
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
const sibling = await listedProduct(m.from.installId);
const sibling = await listedOrRefreshed(m.from.installId, now);
if (!sibling || sibling.product !== m.from.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);
throw new LinkError('The Hub doesn\'t list that install for this church (this site asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { 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);
@@ -87,6 +87,7 @@ const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
async function setUpSite({ linked = true } = {}) {
db.reset();
store.forgetKeyPair();
connect.forgetRefresh();
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
@@ -286,6 +287,29 @@ describe('Connect from a linked product', () => {
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
});
test('3.7.1: a product installed after the last heartbeat is found in a fresh list from the Hub, at most once a minute', async () => {
await store.saveLinkedProducts([]);
const hubClient = require('../src/hub/client');
let listed = [{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }];
const spy = jest.spyOn(hubClient, 'heartbeat').mockImplementation(async () => { await store.saveLinkedProducts(listed); return { ok: true }; });
try {
await connect.acceptConnect(connectMessage(), null, new Date());
expect(spy).toHaveBeenCalledTimes(1);
expect(db.t.productLink.get(WEBSITE_ID)).toMatchObject({ product: 'website' });
// An install the Hub doesn't list: refused, and the Hub isn't asked again within the minute.
listed = [];
await store.saveLinkedProducts([]);
const t = new Date();
await expect(connect.acceptConnect(connectMessage(), null, t)).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(1);
await expect(connect.acceptConnect(connectMessage(), null, new Date(t.getTime() + 61_000))).rejects.toMatchObject({ code: 'NOT_LINKED' });
expect(spy).toHaveBeenCalledTimes(2);
} finally {
spy.mockRestore();
}
});
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
await connect.acceptConnect(connectMessage(), null);
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "3.7.0",
"version": "3.7.1",
"private": true,
"scripts": {
"dev": "next dev",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "3.7.0",
"version": "3.7.1",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+102 -1
View File
@@ -1,6 +1,46 @@
# Changelog — Church Website
## [Unreleased]
## [1.0.2] — 2026-11-26
No migration, no new settings. Works with Accounts 1.7.0; with Accounts 1.7.1 the first sign-in
after an install links at once.
### Fixed
- **Preview sent admins to the server's own address** (`http://localhost:<web port>`, found on
cross-demo2). `/preview/start`, `/preview/exit` and shared preview links redirected to
`new URL(path, request.url)`, and behind the proxy `request.url` is the address Next.js is reached
on. They now answer with a relative `Location` (`src/lib/localRedirect.ts`), so the browser stays
on the site's address.
- **The admin couldn't be signed in to for up to 30 minutes after an install.** The Website links
itself to the church's Accounts, but only at a heartbeat, and Accounts refused it until Accounts'
own next heartbeat. Now opening `/admin` without a link links on the spot (asking the Hub for a
fresh list first when it has no Accounts in it; tried at most every 15 seconds). A connect
involving an install that isn't in the cached list yet (Accounts, or Events for the event feed)
also asks the Hub for a fresh list (at most once a minute) instead of refusing. Only one connect to
Accounts runs at a time, so a heartbeat and a sign-in can't leave the two sides with different
secrets.
- **The sign-in problem page says when the site isn't linked yet** (`ACCOUNTS_NOT_LINKED`: "This
website isn't linked to your church's sign-in yet"), instead of "can't reach your church's
sign-in", which read like an outage.
## [1.0.1] — 2026-11-26
### Fixed
- **The messages' thumbnails come from the site** (WEBSITE-1.0-PLAN §7): they loaded from YouTube
(`i.ytimg.com`) with the page, so every visitor was in touch with YouTube before pressing play.
The backend now fetches a message's thumbnail once and keeps it (`/api/thumbnails/<id>.jpg`,
kept in `uploads/.thumbnails/`, not counted as storage and left out of the export); only the
site's own messages' videos are fetched, and only a JPEG is kept. The messages page asks for the
first one from the `<head>` (it's the largest thing on screen), and the e2e checks that nothing
is asked of YouTube or Spotify until play is clicked.
- **Calendar events' dates** read "Sun (month: November)": a weekday and month without a day is
printed that way by `Intl`. Now "Sun · November".
- **The variant screenshots no longer flake** (e2e only): a section starting at a fractional
position came out a pixel taller or shorter from run to run. The header's and each section's
height is rounded up before the screenshot; the baselines were taken again with it.
## [1.0.0] — 2026-11-26
### Added
@@ -39,6 +79,22 @@
`e2e/screens/`; the admin's flows (edit, preview, publish; discard; a shared link, revoked;
restore; a template switch; a Viewer; signing in from a deep admin page) and axe on every admin
screen.
- **The release checks** (§13): **every section variant in every template** (`e2e/variants.spec.ts`:
26 × 4, axe on each, and 312 screenshots at phone, tablet and desktop compared with the last
baselines, kept on the machine that runs them, not in git); **Lighthouse on a phone**
(`e2e/lighthouse.spec.ts`: home, an event and the messages in each template, the median of three
runs with the CPU slowdown calibrated to the machine: SEO 100, accessibility 95+, performance
90+); and **the same suite on real Postgres**
(`E2E_DATABASE_URL=postgresql://…/<name>_e2e`: the database made again, the migrations applied with
`prisma migrate deploy`). The e2e server's clock is frozen, so the demo's dates are the same every
run.
- **The map loads only once it's on screen** (the With map service times): until then, a link to
it. The iframe's own lazy loading fetched OpenStreetMap's 300 KB script with the page on a phone,
and told OpenStreetMap about every visitor. **The messages page's first thumbnail isn't lazy**
(it's the largest thing on screen), and the page connects to its host at once.
- **Contrast on Bold** (found by the variant checks): the service times' notes on Bold's dark panel
(Panel and With map), and the dates of the Calendar events on a dark band, are light now
(`cc-dark` on the panel; `cc-brand-text`, which the dark rules can override, for the dates).
- **The admin** (§4, §10): a dashboard with the setup checklist, pending changes, storage and notes
about the church's colours; Template and style (the template, each homepage section's layout with
the recommended ones first, the homepage order, the style settings); Pages (details, search
@@ -55,6 +111,51 @@
editing, Publish); a **shared preview link** works signed out for 7 days or until revoked, and
can't change anything. Publish refreshes the public pages at once (`WEBSITE_CONTENT_CACHE_SECONDS`,
30 by default, is how long they're kept otherwise).
- **People** (§10): Owners and Admins add someone by email (their account comes from the church's
Accounts through `people.ensure`, with a "choose your password" email when it's new), change
roles and remove access. Only an Owner touches Owners; nobody changes themselves; a lower role or
removal ends that person's sessions at once. A Ministry leader is tied to their ministry.
- **Messages** (§7): from the church's YouTube channel or playlist automatically (YouTube's public
feed, every hour, no API key; each new video goes live by itself), or by hand with a YouTube or
Spotify link; speaker, series, passage and notes; publish, unpublish, hide. A video is never
added twice; one from the feed can only be hidden (deleting it would bring it back).
- **Simple events** (§8): date and time or all day, place, description, photo and an optional
link; publish, cancel, remove. Both publish on their own, not with the site (decision 9).
- **Photos made safe and fast** (§3): every upload is turned upright, **stripped of its metadata**
(a phone photo can carry where it was taken), kept at most 2400 px wide, and saved at 480, 960
and 1600 px in WebP and JPEG; the pages pick the size the screen needs (`<picture>`, `srcset`).
Every file counts towards storage; a photo the library can't read is refused. (sharp 0.35:
prebuilt binaries, no build step on the servers.)
- **The event feed** (§8, roadmap §4), both ways, as Cross Events 2.4: **Publish my events** serves
the Website's published simple events as `crosscode.event/1` (`GET /api/feed/v1/events`,
`?updatedSince=`; unpublished and removed ones in `deleted` for 90 days) and tells linked siblings
with a signed `event.changed`; **Show events from** fetches each linked sibling's feed every 15
minutes and at once on its signed `event.changed`, keeping read-only copies that link back to the
origin (for registering), only of events that really come from that sibling, one bad event
skipped, and the last good copy kept when a fetch fails. Admin → **Linked products**: Connect,
Disconnect, Show events from, Publish my events, Check now. Accounts' signed `church.changed` now
fetches the church profile again at once.
- **Church details** (§2, decision 10): the church's name, colours, fonts and corners, logo,
service times, contact and social links, saved through Accounts' `church.update` as the signed-in
admin; live at once on all the church's sites (not drafts), refused when someone changed them in
between.
- **Settings** (§10): Google Search Console and Bing verification codes (shown on the home page),
the Coming soon line, and the menu's order. **Audit log** for Owners and Admins; **recent edits**
on the dashboard.
- **Search engines** (§11): a share image made from the church's colours and name for pages without
their own; `Event` structured data on the Website's own event pages, `VideoObject` /
`PodcastEpisode` for messages, `BreadcrumbList` on every page but home; a page's old address
sends people on to the new one (permanent redirect) once published.
- **Two editors at once** (§4): a save that someone else's save overtook is refused, saying who, and
nothing is overwritten. **A Ministry leader's events**: an event can belong to a ministry; its
Ministry leader adds and changes it, an Editor publishes it. **Choose your template** with the
church's own content: each template can be previewed on the real site before it's chosen.
- A simple event with an outside link still has its own page here, with a "More information"
button (its address in the event feed).
- **Get more storage** (§10, decision 12; contracts 1.18.0, Hub 2.22.0): an Owner or Admin asks
under Media library (5 GB steps); the request goes to the Hub, which emails Cross Code, and the
new limit arrives with a heartbeat. The heartbeat now reports the licence's storage limit, so the
Hub emails the church at 80% and when it's full.
- 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.
+2 -2
View File
@@ -9,8 +9,8 @@ presses Publish; until the first publish visitors see Coming soon.
**State:** being built (2026-11-25): signing in through Accounts, the four templates and the public
site, the admin (editing, preview, publish, discard, restore, shared previews, media), and the demo
church. Still to come: managing who has which role, messages and events in the admin (YouTube feed),
responsive image sizes, the event feed, the Hub's "Get more storage", Lighthouse and the VM test. Not released;
church, people and roles, messages (with the YouTube feed), simple events and the event feed with
Cross Events. Still to come: the Hub's "Get more storage", Lighthouse and the VM test. 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
+37
View File
@@ -2,3 +2,40 @@
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).
## 1.0.2
- **Preview works:** pressing Preview in the admin shows your site with your changes, instead of
an error page.
- **Signing in right after your website is installed** works straight away, instead of after up to
half an hour. If it isn't connected to your church's sign-in yet, the page now says so.
## 1.0.1
- **Your visitors' privacy:** the pictures on your messages now come from your own website, so
nothing is loaded from YouTube until someone presses play. The Messages page also shows a little
sooner.
- **Event dates in the Calendar layout** read properly ("Sun · November").
## 1.0.0 — requires accounts 1.7.0
- **Your church's own website**, managed by you. Choose one of four templates (Heritage, Bold,
Community or Clean), then make it yours: each homepage section has two or three layouts, and you
pick the fonts, corners, colours and spacing. Your logo, colours and details come from your
church profile, so the website, Cross Events and your sign-in pages look like one church.
- **Nothing goes live until you say so.** Every change is a draft. Preview the whole site at phone,
tablet and desktop size (and share a preview link), then press **Publish** once. Every published
version is kept, and you can go back to any of them. Until your first Publish, visitors see a
"Coming soon" page.
- **Pages for everything a visitor looks for:** Plan your visit, About, Ministries, Leadership,
Events, Messages, Give and Contact, plus your own pages built from blocks.
- **Messages straight from YouTube:** link your channel or playlist and each new video appears by
itself, or add messages by hand with a YouTube or Spotify link.
- **Events:** add simple events here, and show the events from your Cross Events (with a link to
register there).
- **People and roles:** Owners, Admins, Editors, Ministry leaders (only their own ministry) and
Viewers, all signing in with their church account. An audit log shows who changed what.
- **Found by search engines:** titles and descriptions you can edit, share images, your church on
maps and in local search, and your Google and Bing verification codes.
- **Photos made safe and fast:** location details removed from every photo, and the right size
sent to each screen. 5 GB of uploads included; ask for more under Media library.
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-backend",
"version": "0.1.0",
"version": "1.0.2",
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
"private": true,
"type": "module",
@@ -24,6 +24,7 @@
"@prisma/client": "^7.10.1",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"sharp": "^0.35.5",
"zod": "^4.6.7"
},
"devDependencies": {
@@ -1,4 +1,4 @@
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §10).
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §6, §8, §10).
-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";
@@ -137,6 +137,7 @@ CREATE TABLE "SimpleEvent" (
"description" TEXT,
"imageId" TEXT,
"link" TEXT,
"ministryId" TEXT,
"cancelled" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3),
"updatedAt" TIMESTAMP(3) NOT NULL,
@@ -148,15 +149,25 @@ CREATE TABLE "SimpleEvent" (
-- CreateTable
CREATE TABLE "ImportedEvent" (
"id" TEXT NOT NULL,
"linkId" TEXT NOT NULL,
"originProduct" TEXT NOT NULL,
"originId" TEXT NOT NULL,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" 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 "FeedRemoval" (
"eventId" TEXT NOT NULL,
"removedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "FeedRemoval_pkey" PRIMARY KEY ("eventId")
);
-- CreateTable
CREATE TABLE "MediaAsset" (
"id" TEXT NOT NULL,
@@ -185,6 +196,15 @@ CREATE TABLE "SiteVersion" (
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SlugHistory" (
"slug" TEXT NOT NULL,
"pageId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SlugHistory_pkey" PRIMARY KEY ("slug")
);
-- CreateTable
CREATE TABLE "PreviewLink" (
"id" TEXT NOT NULL,
@@ -234,6 +254,9 @@ CREATE TABLE "ProductLink" (
"secret" TEXT NOT NULL,
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"connectedById" TEXT,
"showEvents" BOOLEAN NOT NULL DEFAULT true,
"lastSyncAt" TIMESTAMP(3),
"lastGoodAt" TIMESTAMP(3),
"lastSyncError" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
@@ -305,6 +328,9 @@ CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
-- CreateIndex
CREATE INDEX "ImportedEvent_linkId_idx" ON "ImportedEvent"("linkId");
-- CreateIndex
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
@@ -332,5 +358,8 @@ ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId"
-- 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 "ImportedEvent" ADD CONSTRAINT "ImportedEvent_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE 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;
+31 -3
View File
@@ -171,6 +171,8 @@ model SimpleEvent {
description String?
imageId String?
link String?
/// A ministry's event: its Ministry leader can add and edit it; an Editor publishes it (§10).
ministryId String?
cancelled Boolean @default(false)
publishedAt DateTime?
updatedAt DateTime @updatedAt
@@ -179,17 +181,29 @@ model SimpleEvent {
@@index([startsAt])
}
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4).
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4). It goes
/// with its link (a disconnect, or "Show events" switched off).
model ImportedEvent {
id String @id @default(uuid())
id String @id @default(uuid())
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
originProduct String
originId String
startsAt DateTime
endsAt DateTime
data Json
syncedAt DateTime @default(now())
syncedAt DateTime @default(now())
@@unique([originProduct, originId])
@@index([startsAt])
@@index([linkId])
}
/// A simple event that left the feed (unpublished or removed), listed in `deleted` for 90 days so
/// siblings drop their copy (ROADMAP-v3 §4).
model FeedRemoval {
eventId String @id
removedAt DateTime @default(now())
}
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
@@ -218,6 +232,14 @@ model SiteVersion {
publishedAt DateTime @default(now())
}
/// A page's earlier address (§6: "Slug changes get a 301 to the new slug"). Published versions
/// send it to wherever the page is now.
model SlugHistory {
slug String @id
pageId String
createdAt 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())
@@ -270,8 +292,14 @@ model ProductLink {
secret String
connectedAt DateTime @default(now())
connectedById String?
/// Show this sibling's events here (the event feed, §8). Accounts has none.
showEvents Boolean @default(true)
lastSyncAt DateTime?
/// The `generatedAt` of the last feed taken: the next fetch asks for what changed since.
lastGoodAt DateTime?
lastSyncError String?
updatedAt DateTime @updatedAt
imported ImportedEvent[]
}
/// Nonces of link messages seen in the last hour (replays are refused).
+52
View File
@@ -0,0 +1,52 @@
/**
* The church's shared details from the Website's admin (WEBSITE-1.0-PLAN §2, decision 10): name,
* colours, brand style (fonts, corners), logo, service times, contact and social links. Accounts
* owns them; the Website saves them through Accounts' `church.update` with the admin as `actor`.
* They aren't drafts: they go live at once on every one of the church's sites, and the screens
* say so. `ifUpdatedAt` refuses a save when someone changed the profile in between.
*/
import { churchEditableSchema, type Church } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { accounts } from '../auth/accounts.js';
import { churchChanged, churchProfile } from '../church/profile.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
type Who = { id: string; role: string };
const patchSchema = churchEditableSchema.extend({ branding: churchEditableSchema.shape.branding.partial() }).partial();
export async function getChurch(ctx: Ctx) {
churchChanged(ctx);
const church = await churchProfile(ctx);
const linked = !!(await ctx.db.productLink.findFirst({ where: { product: 'accounts' } }));
return { church, linked };
}
export async function saveChurch(ctx: Ctx, body: unknown, by: Who): Promise<Church> {
const b = (body ?? {}) as { church?: unknown; ifUpdatedAt?: unknown };
const parsed = patchSchema.safeParse(b.church);
if (!parsed.success) {
const fields: Record<string, string> = {};
for (const i of parsed.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some details need another look.', fields);
}
if (!Object.keys(parsed.data).length) throw new ApiError(400, 'VALIDATION', 'Nothing to change.');
type Reply = { church: Church };
let reply: Reply;
try {
reply = await (await accounts(ctx)).request<Reply>({
type: 'church.update', actor: by.id, church: parsed.data as never,
...(typeof b.ifUpdatedAt === 'string' ? { ifUpdatedAt: b.ifUpdatedAt } : {}),
});
} catch (e) {
const err = e as { code?: string; message?: string; status?: number };
if (err.code === 'PROFILE_CHANGED') throw new ApiError(409, 'PROFILE_CHANGED', 'Someone changed your church\'s details while you were editing. Your changes weren\'t saved: reload to see theirs, then make yours again.');
if (err.code === 'NOT_ALLOWED') throw new ApiError(403, 'NOT_ALLOWED', 'Accounts doesn\'t know you as someone who signs in to this website yet. Sign out and in again, then try once more.');
if (err instanceof ApiError) throw err;
throw new ApiError(err.status && err.status < 500 ? 400 : 502, err.code ?? 'ACCOUNTS_ERROR', err.message ?? 'Accounts didn\'t take the change.');
}
churchChanged(ctx);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'church_details_changed', targetType: 'church', targetId: null, metadata: { fields: Object.keys(parsed.data) } });
return reply.church;
}
+24 -1
View File
@@ -29,6 +29,19 @@ function check<T>(schema: z.ZodType<T>, body: unknown): T {
return r.data;
}
/**
* Two editors at once (§4): a save says when its form was loaded (`ifUpdatedAt`). If someone else
* saved the same thing since, nothing is overwritten and the editor is told who.
*/
export async function notChangedSince(ctx: Ctx, row: { updatedAt: Date; updatedBy: string | null }, body: unknown, by: Who) {
const given = (body as { ifUpdatedAt?: unknown } | null)?.ifUpdatedAt;
if (typeof given !== 'string') return;
const since = new Date(given);
if (!Number.isFinite(since.getTime()) || row.updatedAt.getTime() <= since.getTime() || row.updatedBy === by.id) return;
const other = row.updatedBy ? await ctx.db.websiteUser.findUnique({ where: { id: row.updatedBy } }) : null;
throw new ApiError(409, 'CHANGED_SINCE', `${other?.name ?? 'Someone else'} changed this while you were editing, so your changes weren't saved. Reload to see theirs, then make yours again.`);
}
// ─── Design ───────────────────────────────────────────────────────────────────
export async function getDesign(ctx: Ctx) {
@@ -114,8 +127,14 @@ async function slugFree(ctx: Ctx, slug: string, except?: string) {
export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) {
const page = await getPage(ctx, id);
const patch = check(pagePatch, body);
await notChangedSince(ctx, page, body, by);
if (page.kind === 'home') delete patch.slug;
if (patch.slug && patch.slug !== page.slug) await slugFree(ctx, patch.slug, id);
if (patch.slug && patch.slug !== page.slug) {
await slugFree(ctx, patch.slug, id);
// The old address keeps working: it sends people on to the new one once published.
await ctx.db.slugHistory.upsert({ where: { slug: page.slug }, create: { slug: page.slug, pageId: id }, update: { pageId: id } });
await ctx.db.slugHistory.deleteMany({ where: { slug: patch.slug } });
}
await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } });
return getPage(ctx, id);
}
@@ -152,6 +171,7 @@ export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, bo
if (page.kind !== 'home' || !SECTION_TYPES.includes(type as SectionType)) throw new ApiError(400, 'VALIDATION', 'That isn\'t a homepage section.');
const data = check(schemaFor(type), (body as { data?: unknown })?.data);
const existing = page.sections.find((s) => s.type === type);
if (existing) await notChangedSince(ctx, existing, body, by);
if (existing) await ctx.db.section.update({ where: { id: existing.id }, data: { data: data as never, updatedBy: by.id } });
else await ctx.db.section.create({ data: { pageId, type, position: SECTION_TYPES.indexOf(type as SectionType), data: data as never, updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
@@ -177,6 +197,7 @@ export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, bod
const s = page.sections.find((x) => x.id === sectionId);
if (!s) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
const patch = check(blockPatch, body);
await notChangedSince(ctx, s, body, by);
const data = patch.data === undefined ? undefined : check(schemaFor(s.type), patch.data);
await ctx.db.section.update({ where: { id: sectionId }, data: { ...(data !== undefined ? { data: data as never } : {}), ...(patch.hidden !== undefined ? { hidden: patch.hidden } : {}), ...(patch.variant !== undefined ? { variant: patch.variant } : {}), updatedBy: by.id } });
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
@@ -236,6 +257,7 @@ export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, b
if (id) {
const row = await ctx.db.ministry.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
await notChangedSince(ctx, row, body, by);
return ctx.db.ministry.update({ where: { id }, data });
}
const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
@@ -256,6 +278,7 @@ export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by:
if (id) {
const row = await ctx.db.leader.findUnique({ where: { id } });
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
await notChangedSince(ctx, row, body, by);
return ctx.db.leader.update({ where: { id }, data });
}
const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
@@ -0,0 +1,185 @@
/**
* Messages and simple events in the admin (WEBSITE-1.0-PLAN §7, §8). They're things that happen
* rather than the site's design, so each has its own Publish (decision 9) and doesn't wait for the
* site's. Registrations and payments are only Cross Events' (roadmap decision 4): a simple event has
* at most a link.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { youtubeId, spotifyEmbed, messageThumbnail } from '../site/content.js';
import { mediaUrl } from '../site/snapshot.js';
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
import { markRemoved, notifyLinks } from '../feed/feed.js';
import { notChangedSince } from './content.js';
type Who = { id: string; role: string };
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fields);
}
return r.data;
}
const optional = (max: number) => z.string().trim().max(max).nullable().default(null).transform((v) => v || null);
// ─── Messages ──────────────────────────────────────────────────────────────────
const messageSchema = z.object({
title: z.string().trim().min(1).max(500),
date: z.iso.date().or(z.iso.datetime()),
mediaUrl: z.string().trim().max(500).refine((u) => !!youtubeId(u) || !!spotifyEmbed(u), 'A YouTube video or Spotify episode link'),
speaker: optional(300),
passage: optional(300),
notes: optional(8000),
series: optional(300),
hidden: z.boolean().default(false),
});
async function seriesId(ctx: Ctx, title: string | null) {
if (!title) return null;
const found = await ctx.db.messageSeries.findFirst({ where: { title } });
if (found) return found.id;
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'series';
return (await ctx.db.messageSeries.create({ data: { title, slug: `${slug}-${Date.now().toString(36)}` } })).id;
}
export async function listMessages(ctx: Ctx) {
const [rows, source, lastSync, lastError] = await Promise.all([
ctx.db.message.findMany({ orderBy: { date: 'desc' }, take: 200, include: { series: true } }),
getSource(ctx), ctx.settings.get('youtube_last_sync_at'), ctx.settings.get('youtube_last_error'),
]);
return {
youtube: { source, lastSync, lastError },
items: rows.map((m) => ({
id: m.id, title: m.title, date: m.date.toISOString(), mediaUrl: m.mediaUrl, source: m.source, speaker: m.speaker, passage: m.passage, notes: m.notes,
series: m.series?.title ?? null, hidden: m.hidden, published: m.publishedAt !== null, thumbnail: messageThumbnail(m),
})),
};
}
export async function saveMessage(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const m = check(messageSchema, body);
const yt = youtubeId(m.mediaUrl);
const externalId = yt ?? /\/episode\/([A-Za-z0-9]+)/.exec(m.mediaUrl)?.[1] ?? null;
if (externalId) {
const dup = await ctx.db.message.findFirst({ where: { externalId, ...(id ? { NOT: { id } } : {}) } });
if (dup) throw new ApiError(409, 'DUPLICATE', `That video is already a message (“${dup.title}”).`, { mediaUrl: 'Already a message' });
}
const data = {
title: m.title, date: new Date(m.date), mediaUrl: m.mediaUrl, externalId, speaker: m.speaker, passage: m.passage, notes: m.notes,
seriesId: await seriesId(ctx, m.series), hidden: m.hidden, updatedBy: by.id,
};
if (id) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
// A video from the feed keeps its address and source; its details can be filled in.
const keep = row.source === 'youtube_feed' ? { mediaUrl: row.mediaUrl, externalId: row.externalId } : {};
return ctx.db.message.update({ where: { id }, data: { ...data, ...keep } });
}
return ctx.db.message.create({
data: { ...data, slug: await uniqueSlug(ctx, m.title, 'message'), source: yt ? 'youtube' : 'spotify', thumbnailUrl: yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null },
});
}
/** A message's own Publish (decision 9): live, or back off the site. */
export async function publishMessage(ctx: Ctx, id: string, live: boolean, by: Who) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
await ctx.db.message.update({ where: { id }, data: { publishedAt: live ? ctx.now() : null, updatedBy: by.id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: live ? 'message_published' : 'message_unpublished', targetType: 'message', targetId: id, metadata: { title: row.title } });
}
export async function deleteMessage(ctx: Ctx, id: string, by: Who) {
const row = await ctx.db.message.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That message doesn\'t exist.');
// One from the feed would just come back at the next sync: hide it instead.
if (row.source === 'youtube_feed') throw new ApiError(400, 'FROM_FEED', 'That one comes from YouTube and would come back: hide it instead.');
await ctx.db.message.delete({ where: { id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'message_deleted', targetType: 'message', targetId: id, metadata: { title: row.title } });
}
export async function saveYoutube(ctx: Ctx, body: unknown, by: Who) {
const { youtube } = check(z.object({ youtube: z.string().max(300).nullable() }), body);
const source = await setSource(ctx, youtube);
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'youtube_source_set', targetType: 'setting', targetId: 'youtube_source', metadata: { source } });
return { source, sync: source ? await syncYoutube(ctx) : null };
}
// ─── Simple events ─────────────────────────────────────────────────────────────
const eventSchema = z.object({
title: z.string().trim().min(1).max(300),
startsAt: z.iso.datetime({ offset: true }),
endsAt: z.iso.datetime({ offset: true }).nullable().default(null),
allDay: z.boolean().default(false),
location: optional(500),
description: optional(8000),
imageId: z.string().uuid().nullable().default(null),
ministryId: z.string().uuid().nullable().default(null),
link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null),
}).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] });
export async function listEvents(ctx: Ctx) {
const [rows, media] = await Promise.all([ctx.db.simpleEvent.findMany({ orderBy: { startsAt: 'desc' }, take: 300 }), ctx.db.mediaAsset.findMany()]);
const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)]));
return rows.map((e) => ({
id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location,
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, ministryId: e.ministryId,
cancelled: e.cancelled, published: e.publishedAt !== null, updatedAt: e.updatedAt.toISOString(),
}));
}
const OWN_ONLY = "You can add and change your own ministry's events only.";
export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by: Who) {
const e = check(eventSchema, body);
// A Ministry leader's events are their ministry's (§10); an Editor publishes them.
const leader = by.role === 'ministry_leader' ? await ctx.db.websiteUser.findUnique({ where: { id: by.id } }) : null;
if (leader && (!leader.ministryId || e.ministryId !== leader.ministryId)) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
const data = {
title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description,
imageId: e.imageId, link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
};
if (id) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
if (leader && row.ministryId !== leader.ministryId) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
await notChangedSince(ctx, row, body, by);
const saved = await ctx.db.simpleEvent.update({ where: { id }, data });
// A live event changed: the church's other sites fetch it now.
if (saved.publishedAt) void notifyLinks(ctx, [id]).catch(() => {});
return saved;
}
return ctx.db.simpleEvent.create({ data: { ...data, slug: await uniqueSlug(ctx, e.title, 'simpleEvent') } });
}
export async function setEventState(ctx: Ctx, id: string, change: { published?: boolean; cancelled?: boolean }, by: Who) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
await ctx.db.simpleEvent.update({ where: { id }, data: {
...(change.published !== undefined ? { publishedAt: change.published ? ctx.now() : null } : {}),
...(change.cancelled !== undefined ? { cancelled: change.cancelled } : {}),
updatedBy: by.id,
} });
// In or out of the feed (ROADMAP-v3 §4: an unpublished event goes in `deleted`), and siblings told.
if (change.published !== undefined) await markRemoved(ctx, id, !change.published);
if (row.publishedAt || change.published) void notifyLinks(ctx, [id]).catch(() => {});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_changed', targetType: 'simple_event', targetId: id, metadata: { title: row.title, ...change } });
}
export async function deleteEvent(ctx: Ctx, id: string, by: Who) {
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
await ctx.db.simpleEvent.delete({ where: { id } });
if (row.publishedAt) {
await markRemoved(ctx, id, true);
void notifyLinks(ctx, [id]).catch(() => {});
}
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_deleted', targetType: 'simple_event', targetId: id, metadata: { title: row.title } });
}
+90 -8
View File
@@ -4,16 +4,20 @@
* `limits.storageBytes` says more once extra storage is bought. **When it's full, uploads stop**
* (decision 12) until more is bought; what's already uploaded keeps showing.
*
* Responsive sizes (WebP and JPEG per width) come next; for now the file is served as uploaded.
* Every photo is turned upright and **stripped of its metadata** (a phone photo can carry the place
* it was taken), kept at most 2400 px wide, and saved in responsive sizes (WebP and JPEG at 480,
* 960 and 1600 px wide, each smaller than the photo), all counted towards storage (§3).
*/
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import sharp, { type Metadata, type Sharp } from 'sharp';
import type { Ctx } from '../context.js';
import { defaultUploadDir } from '../demo/demoChurch.js';
import { INCLUDED_STORAGE_BYTES } from '../hub/client.js';
import { hubPublicKey, verifyToken } from '../hub/licence.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
import { mediaUrl } from '../site/snapshot.js';
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
@@ -79,14 +83,92 @@ export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
if (!kind) throw new ApiError(415, 'NOT_AN_IMAGE', 'Upload a photo as JPEG, PNG or WebP.');
const s = await storage(ctx);
if (s.usedBytes + body.length > s.limitBytes) {
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code; everything already uploaded keeps showing.');
throw new ApiError(409, 'STORAGE_FULL', 'Your website\'s storage is full, so uploads have stopped. An Owner or Admin can get more under Media library; everything already uploaded keeps showing.');
}
const now = ctx.now();
const rel = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}.${kind.ext}`;
const file = path.join(uploadDir(ctx), rel);
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, body, { mode: 0o644 });
const { width, height } = dimensions(body, kind);
const row = await ctx.db.mediaAsset.create({ data: { filename: rel, mime: kind.mime, bytes: body.length, width, height, alt: alt.trim().slice(0, 500), uploadedBy: by } });
const base = `${now.getUTCFullYear()}/${String(now.getUTCMonth() + 1).padStart(2, '0')}/${crypto.randomUUID()}`;
const dir = uploadDir(ctx);
await fs.mkdir(path.join(dir, path.dirname(base)), { recursive: true });
const made = await processImage(body, kind, path.join(dir, base));
const bytes = made.files.reduce((t, f) => t + f.bytes, 0);
if (s.usedBytes + bytes > s.limitBytes) {
await Promise.all(made.files.map((f) => fs.rm(path.join(dir, path.dirname(base), f.name), { force: true })));
throw new ApiError(409, 'STORAGE_FULL', 'That photo doesn\'t fit in the storage that\'s left, so it wasn\'t added. An Owner or Admin can get more under Media library.');
}
const filename = `${base}.${made.main.ext}`;
const row = await ctx.db.mediaAsset.create({
data: { filename, mime: made.main.mime, bytes, width: made.width, height: made.height, alt: alt.trim().slice(0, 500), sizes: made.sizes as never, uploadedBy: by },
});
return { ...row, url: mediaUrl(row.filename) };
}
export const MAX_WIDTH = 2400;
export const WIDTHS = [480, 960, 1600] as const;
export type Sizes = { w: number; webp: string; jpg: string }[];
/**
* The photo as kept (upright, no metadata, at most MAX_WIDTH wide, in its own format) and its
* responsive sizes, written next to `basePath` (`<base>.<ext>`, `<base>-<w>.webp`, `<base>-<w>.jpg`).
* A photo the library can't read is refused rather than kept as uploaded.
*/
export async function processImage(body: Buffer, kind: Kind, basePath: string) {
let img: Sharp;
let meta: Metadata;
try {
img = sharp(body, { failOn: 'error' }).rotate();
meta = await img.metadata();
} catch {
throw new ApiError(415, 'NOT_AN_IMAGE', 'That photo can\'t be read. Save it again as JPEG, PNG or WebP and try again.');
}
// After rotate(), width and height follow the EXIF orientation.
const swap = (meta.orientation ?? 1) >= 5;
const fullW = (swap ? meta.height : meta.width) ?? dimensions(body, kind).width ?? MAX_WIDTH;
const fullH = (swap ? meta.width : meta.height) ?? dimensions(body, kind).height ?? null;
const width = Math.min(fullW, MAX_WIDTH);
const height = fullH ? Math.round((fullH * width) / fullW) : null;
const name = path.basename(basePath);
const files: { name: string; bytes: number }[] = [];
const write = async (pipeline: Sharp, file: string) => {
const info = await pipeline.toFile(path.join(path.dirname(basePath), file));
files.push({ name: file, bytes: info.size });
};
// sharp writes no metadata unless asked (withMetadata), so EXIF, GPS and XMP are gone.
const main = kind.ext === 'png' ? { ext: 'png', mime: 'image/png' } : kind.ext === 'webp' ? { ext: 'webp', mime: 'image/webp' } : { ext: 'jpg', mime: 'image/jpeg' };
const resized = () => img.clone().resize({ width, withoutEnlargement: true });
await write(main.ext === 'png' ? resized().png({ compressionLevel: 9 }) : main.ext === 'webp' ? resized().webp({ quality: 82 }) : resized().jpeg({ quality: 82, mozjpeg: true }), `${name}.${main.ext}`);
const sizes: Sizes = [];
for (const w of WIDTHS) {
if (w >= width) continue;
await write(img.clone().resize({ width: w }).webp({ quality: 78 }), `${name}-${w}.webp`);
await write(img.clone().resize({ width: w }).flatten({ background: '#ffffff' }).jpeg({ quality: 80, mozjpeg: true }), `${name}-${w}.jpg`);
sizes.push({ w, webp: `${name}-${w}.webp`, jpg: `${name}-${w}.jpg` });
}
return { main, width, height, sizes, files };
}
type StorageAsk = { at: string; steps: number; limitAtRequest: number };
/** The open "Get more storage" request, if any: open until the limit goes up. */
export async function storageRequestStatus(ctx: Ctx, limitBytes: number): Promise<StorageAsk | null> {
const ask = await ctx.settings.json<StorageAsk | null>('storage_request', null);
return ask && limitBytes <= ask.limitAtRequest ? ask : null;
}
/** "Get more storage": asks the Hub (Cross Code adds it to the licence and is paid R20 a month per step). */
export async function requestMoreStorage(ctx: Ctx, steps: number, by: { id: string; role: string }) {
if (!Number.isInteger(steps) || steps < 1 || steps > 10) throw new ApiError(400, 'VALIDATION', 'Ask for 1 to 10 steps of 5 GB.', { steps: '1 to 10' });
const s = await storage(ctx);
const user = await ctx.db.websiteUser.findUnique({ where: { id: by.id } });
const { requestStorage } = await import('../hub/client.js');
let reply;
try {
reply = await requestStorage(ctx, steps, user?.name ?? null, { usedBytes: s.usedBytes, limitBytes: s.limitBytes });
} catch (e) {
const err = e as { message?: string; code?: string; status?: number };
throw new ApiError(err.status && err.status < 500 ? err.status : 502, err.code ?? 'HUB_ERROR', err.message ?? 'The Hub could not take the request. Try again later.');
}
await ctx.settings.set('storage_request', JSON.stringify({ at: reply.requestedAt, steps: reply.steps, limitAtRequest: s.limitBytes } satisfies StorageAsk));
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'storage_requested', targetType: 'storage', targetId: null, metadata: { steps } });
return { ...reply, request: await storageRequestStatus(ctx, s.limitBytes) };
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Who can use the admin, and as what (WEBSITE-1.0-PLAN §10). Roles are the Website's own, keyed by
* the account's `sub` in the church's Accounts: adding someone by email asks Accounts for their
* account (`people.ensure`), which makes one, with a "choose your password" email, if they have none.
*
* Owner everything, including who is Owner
* Admin everything but Owners (can't add, change or remove one, or make one)
* Others can't manage people
*
* Nobody changes or removes themselves, so a site is never left without an Owner by accident.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import type { WebsiteRole } from '../generated/prisma/client.js';
import { accounts } from '../auth/accounts.js';
import { atLeast, ROLES } from '../auth/sessions.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
type Who = { id: string; role: WebsiteRole };
const roleSchema = z.enum(ROLES as [WebsiteRole, ...WebsiteRole[]]);
const addSchema = z.object({
name: z.string().trim().min(1).max(200),
email: z.email().trim().toLowerCase().max(254),
role: roleSchema,
ministryId: z.string().uuid().nullable().default(null),
});
const changeSchema = z.object({ role: roleSchema, ministryId: z.string().uuid().nullable().default(null) });
function check<T>(schema: z.ZodType<T>, body: unknown): T {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fields);
}
return r.data;
}
/** May `by` give (or take) `role`? */
function mayManage(by: Who, role: WebsiteRole) {
if (!atLeast(by.role, 'admin')) throw new ApiError(403, 'FORBIDDEN', 'Only an Owner or Admin can manage who has access.');
if (role === 'owner' && by.role !== 'owner') throw new ApiError(403, 'OWNERS_ONLY', 'Only an Owner can add, change or remove an Owner.');
}
async function ministryFor(ctx: Ctx, role: WebsiteRole, ministryId: string | null) {
if (role !== 'ministry_leader') return null;
if (!ministryId) throw new ApiError(400, 'VALIDATION', 'Choose the ministry they lead.', { ministryId: 'Choose their ministry' });
const m = await ctx.db.ministry.findUnique({ where: { id: ministryId } });
if (!m || m.archivedAt) throw new ApiError(400, 'VALIDATION', 'That ministry doesn\'t exist.', { ministryId: 'Not a ministry' });
return ministryId;
}
export async function listPeople(ctx: Ctx) {
const [users, ministries] = await Promise.all([ctx.db.websiteUser.findMany({ orderBy: { name: 'asc' } }), ctx.db.ministry.findMany()]);
const names = new Map(ministries.map((m) => [m.id, m.name]));
return users.map((u) => ({
id: u.id, name: u.name, email: u.email, role: u.role, ministryId: u.ministryId, ministry: u.ministryId ? names.get(u.ministryId) ?? null : null,
lastSignInAt: u.lastSignInAt?.toISOString() ?? null,
}));
}
export async function addPerson(ctx: Ctx, body: unknown, by: Who) {
const p = check(addSchema, body);
mayManage(by, p.role);
const ministryId = await ministryFor(ctx, p.role, p.ministryId);
const reply = await (await accounts(ctx)).request<{ sub: string; created: boolean; emailSent?: boolean }>({
type: 'people.ensure', actor: by.id, name: p.name, email: p.email, phone: null, returnUrl: `${ctx.config.publicUrl}/admin`,
});
if (await ctx.db.websiteUser.findUnique({ where: { id: reply.sub } })) throw new ApiError(409, 'ALREADY_ADDED', 'They already have access. Change their role instead.');
const user = await ctx.db.websiteUser.create({ data: { id: reply.sub, name: p.name, email: p.email, role: p.role, ministryId } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_added', targetType: 'website_user', targetId: user.id, metadata: { role: p.role, newAccount: reply.created } });
return { id: user.id, newAccount: reply.created, emailSent: reply.emailSent ?? null };
}
async function target(ctx: Ctx, id: string, by: Who) {
if (id === by.id) throw new ApiError(400, 'SELF', 'You can\'t change or remove your own access. Ask another Owner or Admin.');
const user = await ctx.db.websiteUser.findUnique({ where: { id } });
if (!user) throw new ApiError(404, 'NOT_FOUND', 'That person doesn\'t have access.');
mayManage(by, user.role);
return user;
}
export async function changePerson(ctx: Ctx, id: string, body: unknown, by: Who) {
const user = await target(ctx, id, by);
const c = check(changeSchema, body);
mayManage(by, c.role);
const ministryId = await ministryFor(ctx, c.role, c.ministryId);
await ctx.db.websiteUser.update({ where: { id }, data: { role: c.role, ministryId } });
// A lower role takes effect at once: their sessions end, and they sign in again.
if (ROLES.indexOf(c.role) < ROLES.indexOf(user.role)) await ctx.db.session.deleteMany({ where: { userId: id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_role_changed', targetType: 'website_user', targetId: id, metadata: { from: user.role, to: c.role } });
return { ok: true };
}
export async function removePerson(ctx: Ctx, id: string, by: Who) {
const user = await target(ctx, id, by);
await ctx.db.session.deleteMany({ where: { userId: id } });
await ctx.db.websiteUser.delete({ where: { id } });
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'website_user_removed', targetType: 'website_user', targetId: id, metadata: { role: user.role } });
return { ok: true };
}
+101 -6
View File
@@ -14,7 +14,15 @@ import { mediaUrl, publish } from '../site/snapshot.js';
import { TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_VARIANTS } from '../site/variants.js';
import { changes, discard, restore } from '../site/workingCopy.js';
import * as content from './content.js';
import { MAX_UPLOAD_BYTES, storage, upload } from './media.js';
import * as people from './people.js';
import * as church from './church.js';
import * as settings from './settings.js';
import * as happenings from './happenings.js';
import { syncYoutube } from '../site/youtube.js';
import { publishOn, syncLink } from '../feed/feed.js';
import { connectTo, disconnectFrom } from '../links/connect.js';
import { linkedProducts } from '../links/store.js';
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
@@ -31,19 +39,21 @@ export function adminRouter(ctx: Ctx) {
/** The dashboard: pending changes, the last publish, storage, and the setup checklist (§10). */
r.get('/overview', handle(async () => {
const [pending, last, s, church, design, pages, ministries] = await Promise.all([
const [pending, last, s, profile, design, pages, ministries, recent] = await Promise.all([
changes(ctx), ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } }), storage(ctx), churchProfile(ctx),
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx),
ctx.db.siteDesign.findUnique({ where: { id: 1 } }), content.listPages(ctx), content.listMinistries(ctx), settings.auditLog(ctx, { take: 12 }),
]);
const palette = church ? buildPalette(church.branding.colours.primary, church.branding.colours.accent) : null;
const palette = profile ? buildPalette(profile.branding.colours.primary, profile.branding.colours.accent) : null;
return {
pending: pending.length,
/** Recent edits (§10): the audit log without sign-ins. */
recent: recent.filter((e) => !/^(Signed|Was refused)/.test(e.action)).slice(0, 5),
lastPublished: last ? { number: last.number, at: last.publishedAt.toISOString() } : null,
storage: s,
colourNotes: palette?.notes ?? [],
checklist: [
{ key: 'template', label: 'Choose your template', done: !!design, href: '/admin/template' },
{ key: 'profile', label: 'Add your service times and address (your church profile in Accounts)', done: !!church && church.serviceTimes.length > 0 && !!church.contact.address, href: null },
{ key: 'profile', label: 'Add your service times and address', done: !!profile && profile.serviceTimes.length > 0 && !!profile.contact.address, href: '/admin/church' },
{ key: 'pages', label: 'Write your home page and Plan your visit', done: pages.some((p) => p.kind === 'visit'), href: '/admin/pages' },
{ key: 'ministries', label: 'Add your ministries', done: ministries.length > 0, href: '/admin/ministries' },
{ key: 'publish', label: 'Preview and publish', done: !!last, href: '/admin/publish' },
@@ -86,10 +96,13 @@ export function adminRouter(ctx: Ctx) {
// ─── Media library and storage ───
r.get('/media', handle(async () => {
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
return { storage: await storage(ctx), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
const s = await storage(ctx);
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
}));
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
// Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
r.post('/storage-request', requireRole(ctx, 'admin'), json, handle((req) => requestMoreStorage(ctx, Number(req.body?.steps ?? 1), who(req))));
r.put('/media/:id', editor, json, handle(async (req) => {
const alt = String(req.body?.alt ?? '').trim().slice(0, 500);
const m = await ctx.db.mediaAsset.update({ where: { id: param(req, 'id') }, data: { alt } }).catch(() => null);
@@ -97,6 +110,88 @@ export function adminRouter(ctx: Ctx) {
return { id: m.id, alt: m.alt };
}));
// ─── Messages and simple events: each publishes on its own (decision 9) ───
r.get('/messages', handle(() => happenings.listMessages(ctx)));
r.post('/messages', editor, json, handle((req) => happenings.saveMessage(ctx, null, req.body, who(req))));
r.put('/messages/:id', editor, json, handle((req) => happenings.saveMessage(ctx, param(req, 'id'), req.body, who(req))));
r.post('/messages/:id/publish', editor, json, handle(async (req) => { await happenings.publishMessage(ctx, param(req, 'id'), req.body?.live !== false, who(req)); return { ok: true }; }));
r.delete('/messages/:id', editor, handle(async (req) => { await happenings.deleteMessage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
r.put('/messages-youtube', editor, json, handle((req) => happenings.saveYoutube(ctx, req.body, who(req))));
r.post('/messages-youtube/sync', editor, handle(() => syncYoutube(ctx)));
r.get('/events', handle(() => happenings.listEvents(ctx)));
// An Editor, or a Ministry leader for their own ministry's events (checked in saveEvent).
const eventWriter = requireRole(ctx, 'ministry_leader');
r.post('/events', eventWriter, json, handle((req) => happenings.saveEvent(ctx, null, req.body, who(req))));
r.put('/events/:id', eventWriter, json, handle((req) => happenings.saveEvent(ctx, param(req, 'id'), req.body, who(req))));
r.post('/events/:id/state', editor, json, handle(async (req) => {
const b = req.body ?? {};
await happenings.setEventState(ctx, param(req, 'id'), { ...(typeof b.published === 'boolean' ? { published: b.published } : {}), ...(typeof b.cancelled === 'boolean' ? { cancelled: b.cancelled } : {}) }, who(req));
return { ok: true };
}));
r.delete('/events/:id', editor, handle(async (req) => { await happenings.deleteEvent(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
// ─── The church's shared details (through Accounts, live at once), settings, audit log ───
r.get('/church', handle(() => church.getChurch(ctx)));
r.put('/church', editor, json, handle((req) => church.saveChurch(ctx, req.body, who(req))));
r.get('/settings', handle(() => settings.getSettings(ctx)));
r.put('/settings', editor, json, handle((req) => settings.saveSettings(ctx, req.body, who(req))));
r.put('/pages-order', editor, json, handle((req) => settings.orderPages(ctx, req.body, who(req))));
r.get('/audit', requireRole(ctx, 'admin'), handle((req) => settings.auditLog(ctx, { before: typeof req.query.before === 'string' ? req.query.before : undefined })));
// ─── Linked products and the event feed (§8, §9) ───
r.get('/links', handle(async () => {
const [listed, links, publishing] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany(), publishOn(ctx)]);
const counts = new Map<string, number>();
for (const l of links) counts.set(l.installId, await ctx.db.importedEvent.count({ where: { linkId: l.installId } }));
const ids = new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)]);
return {
publishMyEvents: publishing,
products: [...ids].map((id) => {
const l = listed.find((x) => x.installId === id);
const link = links.find((x) => x.installId === id);
return {
installId: id, product: link?.product ?? l!.product, url: link?.url ?? l!.url, connected: !!link, listed: !!l,
showEvents: link?.showEvents ?? null, events: counts.get(id) ?? 0,
lastSyncAt: link?.lastSyncAt?.toISOString() ?? null, lastSyncError: link?.lastSyncError ?? null,
};
}),
};
}));
const linkAdmin = requireRole(ctx, 'admin');
r.post('/links/:id/connect', linkAdmin, handle(async (req) => {
const link = await connectTo(ctx, param(req, 'id'), who(req), req);
if (link.product !== 'accounts') await syncLink(ctx, link);
return { ok: true };
}));
r.delete('/links/:id', linkAdmin, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (link?.product === 'accounts') throw new ApiError(400, 'ACCOUNTS', 'The Website signs in through Accounts, so that link stays.');
return disconnectFrom(ctx, param(req, 'id'), who(req), req);
}));
r.put('/links/:id', editor, json, handle(async (req) => {
const id = param(req, 'id');
const link = await ctx.db.productLink.findUnique({ where: { installId: id } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
const updated = await ctx.db.productLink.update({ where: { installId: id }, data: { showEvents: !!req.body?.showEvents } });
return syncLink(ctx, updated);
}));
r.post('/links/:id/sync', editor, handle(async (req) => {
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
return syncLink(ctx, link);
}));
r.put('/feed', editor, json, handle(async (req) => {
await ctx.settings.set('feed_publish', req.body?.publish === false ? 'false' : 'true');
return { publishMyEvents: await publishOn(ctx) };
}));
// ─── People: who can use the admin, as what (Owner and Admin) ───
const admin = requireRole(ctx, 'admin');
r.get('/people', admin, handle(() => people.listPeople(ctx)));
r.post('/people', admin, json, handle((req) => people.addPerson(ctx, req.body, who(req))));
r.put('/people/:id', admin, json, handle((req) => people.changePerson(ctx, param(req, 'id'), req.body, who(req))));
r.delete('/people/:id', admin, handle((req) => people.removePerson(ctx, param(req, 'id'), who(req))));
// ─── Publish, discard, restore, versions, shared previews (§4) ───
r.get('/changes', handle(() => changes(ctx)));
r.post('/publish', editor, json, handle(async (req) => {
@@ -0,0 +1,93 @@
/**
* The site's own settings (WEBSITE-1.0-PLAN §10, "Settings"), live at once (they aren't the site's
* design): the Coming soon line (§5), and the search engines' verification codes (ROADMAP-v3 §11:
* Google Search Console and Bing Webmaster Tools), shown as `<meta>` tags on the home page. Also the
* menu's order, and the audit log.
*/
import { z } from 'zod';
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
import { audit } from '../lib/audit.js';
/** What the search engines give: the content of their meta tag, or the whole tag pasted in. */
const code = z.string().trim().max(300)
.transform((v) => (/content="([^"]+)"/.exec(v)?.[1] ?? v).trim())
.refine((v) => v === '' || /^[\w-]{6,100}$/.test(v), 'The code from the search engine (letters, numbers, - and _)');
const schema = z.object({
comingSoonText: z.string().trim().max(300).optional(),
googleVerification: code.optional(),
bingVerification: code.optional(),
});
export type SiteSettings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
export async function getSettings(ctx: Ctx): Promise<SiteSettings> {
const [coming, google, bing] = await Promise.all([ctx.settings.get('coming_soon_text'), ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
return { comingSoonText: coming || 'Our new website is on its way.', googleVerification: google || null, bingVerification: bing || null };
}
export async function saveSettings(ctx: Ctx, body: unknown, by: { id: string; role: string }) {
const r = schema.safeParse(body);
if (!r.success) {
const fields: Record<string, string> = {};
for (const i of r.error.issues) fields[i.path.join('.') || '_'] ??= i.message;
throw new ApiError(400, 'VALIDATION', 'Some settings need another look.', fields);
}
const s = r.data;
await ctx.settings.setMany({
...(s.comingSoonText !== undefined ? { coming_soon_text: s.comingSoonText || null } : {}),
...(s.googleVerification !== undefined ? { google_verification: s.googleVerification || null } : {}),
...(s.bingVerification !== undefined ? { bing_verification: s.bingVerification || null } : {}),
});
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'settings_changed', targetType: 'settings', targetId: null, metadata: { fields: Object.keys(s) } });
return getSettings(ctx);
}
/** The menu's order: pages in the order given (§10, "Navigation"). A draft, like any page change. */
export async function orderPages(ctx: Ctx, body: unknown, by: { id: string }) {
const ids = z.array(z.string().uuid()).max(200).safeParse((body as { ids?: unknown } | null)?.ids);
if (!ids.success) throw new ApiError(400, 'VALIDATION', 'Give the pages in order.');
const pages = await ctx.db.page.findMany({ where: { archivedAt: null } });
const known = new Set(pages.map((p) => p.id));
if (ids.data.some((id) => !known.has(id))) throw new ApiError(400, 'VALIDATION', "That isn't one of the site's pages.");
for (const [n, id] of ids.data.entries()) {
const p = pages.find((x) => x.id === id)!;
if (p.position !== n + 1) await ctx.db.page.update({ where: { id }, data: { position: n + 1, updatedBy: by.id } });
}
return { ok: true };
}
const ACTIONS: Record<string, string> = {
site_published: 'Published the site', change_discarded: 'Discarded a change', version_restored: 'Restored a version',
preview_link_created: 'Made a preview link', preview_link_revoked: 'Stopped a preview link',
first_owner_signed_in: 'Signed in as the first Owner', admin_signed_in: 'Signed in', admin_signed_out: 'Signed out',
admin_sign_in_refused: 'Was refused sign-in (no role here)', website_user_added: 'Gave someone access',
website_user_role_changed: "Changed someone's role", website_user_removed: "Removed someone's access",
website_user_deleted: 'An account was deleted in Accounts', message_published: 'Published a message',
message_unpublished: 'Took a message off the site', message_deleted: 'Removed a message',
youtube_source_set: 'Set the YouTube channel or playlist', event_changed: 'Changed an event', event_deleted: 'Removed an event',
church_details_changed: "Changed the church's details", settings_changed: 'Changed the settings',
product_link_connected: 'Connected a product', product_link_disconnected: 'Disconnected a product', storage_requested: 'Asked for more storage',
};
const ROLE_ACTORS: Record<string, string> = { system: 'The site itself', linked_product: 'A linked product', accounts: 'Accounts' };
/** The audit log (§4: "an audit log of who changed what"), newest first. */
export async function auditLog(ctx: Ctx, opts: { before?: string; take?: number } = {}) {
const take = Math.min(200, Math.max(1, opts.take ?? 100));
const before = opts.before ? new Date(opts.before) : null;
const where = before && Number.isFinite(before.getTime()) ? { createdAt: { lt: before } } : {};
const rows = await ctx.db.auditLog.findMany({ where, orderBy: { createdAt: 'desc' }, take });
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
return rows.map((r) => {
const meta = (r.metadata ?? {}) as Record<string, unknown>;
const detail = [meta.title, meta.label, meta.note].find((x) => typeof x === 'string') as string | undefined;
return {
at: r.createdAt.toISOString(),
who: (r.actorId && names.get(r.actorId)) || ROLE_ACTORS[r.actorRole] || 'Someone',
action: ACTIONS[r.action] ?? r.action.replace(/_/g, ' '),
detail: detail ?? null,
};
});
}
+24 -1
View File
@@ -5,6 +5,7 @@
* /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/uploads/… the church's uploaded images
* /api/thumbnails/<id>.jpg its messages' YouTube thumbnails, kept here (visitors never ask YouTube)
* /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
@@ -14,6 +15,7 @@
*/
import path from 'node:path';
import express from 'express';
import { websiteTemplateSchema } from '@crosscode/contracts';
import type { Ctx } from './context.js';
import { authRouter } from './auth/routes.js';
import { adminRouter } from './admin/routes.js';
@@ -26,6 +28,7 @@ import { linksRouter } from './links/routes.js';
import { defaultUploadDir } from './demo/demoChurch.js';
import { previewContent, siteContent } from './site/content.js';
import { siteStatus } from './site/status.js';
import { thumbnail } from './site/thumbnails.js';
export function createApp(ctx: Ctx) {
const app = express();
@@ -53,7 +56,10 @@ export function createApp(ctx: Ctx) {
if (!signed && !(await previewTokenValid(ctx, req.get('x-preview-token')))) throw new ApiError(401, 'NO_PREVIEW', 'This preview has ended, or you need to sign in.');
res.set('Cache-Control', 'no-store');
res.set('X-Robots-Tag', 'noindex, nofollow');
return { ...(await previewContent(ctx)), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') } };
// An admin trying a template on (Template and style): the content in it, nothing saved.
const t = websiteTemplateSchema.safeParse(req.get('x-preview-template'));
const asTemplate = signed && t.success ? t.data : undefined;
return { ...(await previewContent(ctx, { asTemplate })), preview: { by: signed ? 'admin' : 'link', canPublish: !!signed && atLeast(signed.user.role, 'editor') && !asTemplate, template: asTemplate ?? null } };
}));
site.get('/content', handle(async (_req, res) => {
// Short: Publish shows within a minute even where a proxy caches.
@@ -71,6 +77,23 @@ export function createApp(ctx: Ctx) {
},
}));
// A message's YouTube thumbnail, fetched once by the backend and kept (site/thumbnails.ts).
app.get('/api/thumbnails/:file', async (req, res, next) => {
try {
const id = /^([A-Za-z0-9_-]+)\.jpg$/.exec(req.params.file)?.[1];
const body = id ? await thumbnail(ctx, id) : null;
if (!body) {
res.set('Cache-Control', 'no-store');
return sendError(res, new ApiError(404, 'NOT_FOUND', 'There is no such file.'));
}
res.set('Content-Type', 'image/jpeg');
res.set('Cache-Control', 'public, max-age=604800');
res.send(body);
} catch (err) {
next(err);
}
});
app.use('/api', authRouter(ctx));
app.use('/api', linksRouter(ctx));
+11 -4
View File
@@ -8,13 +8,15 @@ 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';
import { linkAccountsNow } from '../links/connect.js';
export type AuthClientModule = typeof AuthClient;
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
export class AccountsUnavailable extends ApiError {
constructor(message: string) {
/** 1.0.2: `not_linked` (no link to Accounts yet) or `unreachable` (linked, but it didn't answer). */
constructor(message: string, public reason: 'not_linked' | 'unreachable' = 'unreachable') {
super(503, 'ACCOUNTS_UNAVAILABLE', message);
}
}
@@ -28,10 +30,15 @@ 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.');
let link = await accountsLink(ctx);
if (!link) {
// 1.0.2: link now rather than wait for the next heartbeat.
await linkAccountsNow(ctx);
link = await accountsLink(ctx);
}
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet.', 'not_linked');
const clientId = await ctx.settings.get('hub_install_id');
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.');
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.', 'not_linked');
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
let hit = cache.get(ctx);
if (!hit || hit.key !== key) {
+5 -2
View File
@@ -34,6 +34,9 @@ const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${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))}`));
/** 1.0.2: the problem page says which it is: not linked to Accounts yet, or Accounts not answering. */
const unavailableCode = (e: AccountsUnavailable) => (e.reason === 'not_linked' ? 'ACCOUNTS_NOT_LINKED' : 'ACCOUNTS_UNAVAILABLE');
type UserRow = { id: string; name: string; email: string; role: WebsiteRole };
/**
@@ -70,7 +73,7 @@ export function authRouter(ctx: Ctx) {
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);
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e), returnTo);
console.error('[auth] Starting a sign-in failed:', e);
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
}
@@ -86,7 +89,7 @@ export function authRouter(ctx: Ctx) {
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');
if (e instanceof AccountsUnavailable) return problem(ctx, res, unavailableCode(e));
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, '/'));
+4 -1
View File
@@ -18,13 +18,16 @@ export type Ctx = {
/** `@crosscode/auth-client` (tests give a stand-in). */
authClient: () => Promise<AuthClientModule>;
now: () => Date;
/** Fetches what visitors are shown from outside (YouTube's thumbnails); tests give a stand-in. */
fetch?: (url: string) => Promise<Response>;
};
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule> } = {}): Ctx {
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule>; fetch?: (url: string) => Promise<Response> } = {}): 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());
if (opts.fetch) partial.fetch = opts.fetch;
return partial;
}
+1 -1
View File
@@ -48,7 +48,7 @@ export function demoProfile(publicUrl: string): Church {
}
/** An illustrated "photo": hills, a sun and a path in the church's colours (SVG, no people). */
function illustration(seed: number, w = 1600, h = 1000): string {
export function illustration(seed: number, w = 1600, h = 1000): string {
const hues = [DEMO_COLOURS.primary, DEMO_COLOURS.accent, '#7fb7be', '#f3e3c3', '#284b52'];
const c = (i: number) => hues[(seed + i) % hues.length];
const y = (f: number) => Math.round(h * f);
+173
View File
@@ -0,0 +1,173 @@
/**
* The event feed (WEBSITE-1.0-PLAN §8, ROADMAP-v3 §4), both ways, as Cross Events 2.4:
*
* - **Publish my events** (AppSetting `feed_publish`, on by default): the Website's published simple
* events as `crosscode.event/1` at `GET /api/feed/v1/events?updatedSince=`, with removed ones in
* `deleted` for 90 days. Only events it made itself, never ones it imported (no loops).
* - **Show events from** each linked sibling (`ProductLink.showEvents`): fetched every 15 minutes and
* at once on its signed `event.changed`; read-only copies, the last good copy kept when a fetch
* fails, one bad event skipped without holding up the rest, and only events that really come
* from that sibling.
* - Linked siblings are told (`event.changed`) when one of the Website's events changes.
*/
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventSchema, FEED_PATHS, parseEventFeed, type CrosscodeEvent, type EventChanged, type EventFeed } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { callSibling, siblingUrl } from '../links/http.js';
import { imageOf } from '../site/snapshot.js';
const DAY = 864e5;
export const ENDED_KEEP_DAYS = 30;
export const REMOVED_KEEP_DAYS = 90;
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
const OVERLAP_MS = 5 * 60 * 1000;
export const publishOn = (ctx: Ctx) => ctx.settings.bool('feed_publish', true);
type SimpleRow = {
id: string; slug: string; title: string; startsAt: Date; endsAt: Date | null; allDay: boolean; timezone: string; location: string | null;
description: string | null; imageId: string | null; link: string | null; cancelled: boolean; updatedAt: Date;
};
/** One of the Website's simple events as `crosscode.event/1`. */
export function toCrosscodeEvent(ctx: Ctx, e: SimpleRow, installId: string, imageUrl: string | null): CrosscodeEvent {
const url = `${ctx.config.publicUrl}/events/${e.slug}`;
const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3));
return {
schema: EVENT_SCHEMA,
id: e.id,
origin: { product: 'website', installId, url },
status: e.cancelled ? 'cancelled' : 'published',
updatedAt: e.updatedAt.toISOString(),
title: e.title.slice(0, 200),
summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 300) : null,
description: e.description,
imageUrl,
timezone: e.timezone,
startsAt: e.startsAt.toISOString(),
endsAt: ends.toISOString(),
allDay: e.allDay,
sessions: [],
location: e.location ? { name: e.location.slice(0, 200), address: null, onlineUrl: null } : null,
campus: null,
series: null,
tags: [],
// Only Cross Events takes registrations: a link, or nothing (roadmap decision 4).
registration: e.link ? { mode: 'external', url: e.link, status: 'open', opensAt: null, closesAt: null, priceFrom: null } : { mode: 'none', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null },
} as CrosscodeEvent;
}
/** `GET /api/feed/v1/events`: what changed since `since` (everything when null). */
export async function buildFeed(ctx: Ctx, since: Date | null): Promise<EventFeed> {
const now = ctx.now();
const installId = (await ctx.settings.get('hub_install_id'))!;
const [rows, media, removals] = await Promise.all([
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, startsAt: { gte: new Date(now.getTime() - (ENDED_KEEP_DAYS + 30) * DAY) } }, orderBy: { startsAt: 'asc' } }),
ctx.db.mediaAsset.findMany(),
ctx.db.feedRemoval.findMany({ where: { removedAt: { gte: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY), ...(since ? { gt: since } : {}) } } }),
]);
const byId = new Map(media.map((m) => [m.id, m]));
const events: CrosscodeEvent[] = [];
for (const row of rows) {
const ends = row.endsAt ?? row.startsAt;
if (ends.getTime() < now.getTime() - ENDED_KEEP_DAYS * DAY) continue;
if (since && row.updatedAt <= since) continue;
const m = row.imageId ? byId.get(row.imageId) : null;
const e = toCrosscodeEvent(ctx, row, installId, m ? `${ctx.config.publicUrl}${imageOf(m).url}` : null);
// Never publish something the contract refuses.
if (eventSchema.safeParse(e).success) events.push(e);
}
return { schema: EVENT_FEED_SCHEMA, generatedAt: now.toISOString(), events, deleted: removals.map((r) => ({ id: r.eventId, deletedAt: r.removedAt.toISOString() })) };
}
/** A simple event left the feed: siblings drop their copy. Back on it (published again): no longer removed. */
export async function markRemoved(ctx: Ctx, eventId: string, removed: boolean) {
if (removed) await ctx.db.feedRemoval.upsert({ where: { eventId }, create: { eventId, removedAt: ctx.now() }, update: { removedAt: ctx.now() } });
else await ctx.db.feedRemoval.deleteMany({ where: { eventId } });
}
/** Tells every linked sibling (not Accounts) that these events changed. One try; their poll catches up. */
export async function notifyLinks(ctx: Ctx, eventIds: string[]): Promise<{ told: number; failed: number }> {
if (!eventIds.length || !(await publishOn(ctx))) return { told: 0, failed: 0 };
const senderId = await ctx.settings.get('hub_install_id');
if (!senderId) return { told: 0, failed: 0 };
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: ctx.now().toISOString(), eventIds: eventIds.slice(0, 100) };
const raw = JSON.stringify(body);
let told = 0;
let failed = 0;
await Promise.all(links.map(async (link) => {
try {
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: ctx.secrets.decrypt(link.secret), rawBody: raw });
await callSibling(await siblingUrl(ctx, link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
told++;
} catch (e) {
failed++;
console.warn(`[feed] event.changed to ${link.url} failed (its poll will catch up):`, (e as Error).message);
}
}));
return { told, failed };
}
type LinkRow = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string };
/** Fetches one sibling's feed into read-only copies. */
export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 };
if (!link.showEvents) {
const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count;
return { installId: link.installId, ok: true, imported: 0, deleted: gone };
}
const now = ctx.now();
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
try {
const url = await siblingUrl(ctx, link.url, FEED_PATHS.events);
if (since) url.searchParams.set('updatedSince', since.toISOString());
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1 (${parsed.error.issues.slice(0, 2).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')})`);
const { feed, rejected } = parsed;
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`})`);
// Only events that really come from this sibling: one product can't speak for another.
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
for (const e of theirs) {
const data = { linkId: link.installId, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), data: e as never, syncedAt: now };
const existing = await ctx.db.importedEvent.findFirst({ where: { originProduct: e.origin.product, originId: e.id } });
if (existing) await ctx.db.importedEvent.update({ where: { id: existing.id }, data });
else await ctx.db.importedEvent.create({ data: { ...data, originProduct: e.origin.product, originId: e.id } });
}
let deleted = 0;
for (const d of feed.deleted) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: d.id } })).count;
// A full fetch is the whole list: anything not in it is gone.
if (!since) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: { notIn: theirs.map((e) => e.id) } } })).count;
await ctx.db.productLink.update({
where: { installId: link.installId },
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
});
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length };
} catch (e) {
const error = String((e as Error)?.message || e).slice(0, 500);
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
return { installId: link.installId, ok: false, error };
}
}
/** Every linked sibling, one after another; one failing never stops the rest. */
export async function syncAll(ctx: Ctx) {
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
let failed = 0;
for (const link of links) if (!(await syncLink(ctx, link)).ok) failed++;
return { links: links.length, failed };
}
/** Every 15 minutes (ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback"). */
export function startFeedSync(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const run = () => syncAll(ctx).catch((e) => console.warn('[feed]', (e as Error).message));
const first = setTimeout(run, 20_000);
const timer = setInterval(run, 15 * 60 * 1000);
first.unref?.();
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}
+20 -2
View File
@@ -14,6 +14,7 @@ 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';
import { storage } from '../admin/media.js';
export const PROTOCOL_VERSION = 2;
const TIMEOUT_MS = 15000;
@@ -81,7 +82,7 @@ export async function stats(ctx: Ctx) {
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 } }),
storage(ctx),
]);
return {
// Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions).
@@ -89,7 +90,9 @@ export async function stats(ctx: Ctx) {
messages: { total, last30d },
events: { upcomingSimple, imported },
editors,
storage: { usedBytes: media._sum.bytes ?? 0, includedBytes: INCLUDED_STORAGE_BYTES },
// The limit the licence gives (5 GB plus steps bought): the Hub emails the church's admin at
// 80% and 100% (decision 12).
storage: { usedBytes: media.usedBytes, includedBytes: media.limitBytes },
};
}
@@ -196,3 +199,18 @@ export function startHeartbeats(ctx: Ctx): () => void {
timer.unref?.();
return () => clearInterval(timer);
}
/**
* "Get more storage" (WEBSITE-1.0-PLAN §10, decision 12; contracts 1.18.0): asks the Hub for more
* 5 GB steps. The Hub emails Cross Code; the new limit arrives with a later heartbeat answer.
*/
export async function requestStorage(ctx: Ctx, steps: number, requestedBy: string | null, now: { usedBytes: number; limitBytes: number }) {
const installId = await ctx.settings.get('hub_install_id');
const secret = await ctx.settings.get('hub_install_secret');
if (!installId || !secret) throw new HubError('This site isn\'t connected to the Hub yet, so it can\'t ask for more storage.', 'NOT_CONNECTED', 503);
const body = hub.storageRequestSchema.parse({ protocolVersion: PROTOCOL_VERSION, steps, usedBytes: now.usedBytes, limitBytes: now.limitBytes, requestedBy });
const data = await post(ctx, '/api/installs/storage-request', body, { installId, secret });
const reply = hub.storageRequestResponseSchema.safeParse(data);
if (!reply.success) throw new HubError('The Hub answered in a way this site doesn\'t understand.', 'BAD_REPLY', 502);
return reply.data;
}
+8 -2
View File
@@ -1,8 +1,8 @@
/**
* 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).
* Accounts once the Hub lists it, and the hourly YouTube feed (§7). The other jobs (storage emails,
* the event feed) come with their features (docs/WEBSITE-1.0-PLAN.md §1).
*/
import 'dotenv/config';
import { PrismaPg } from '@prisma/adapter-pg';
@@ -11,6 +11,8 @@ import { createApp } from './app.js';
import { createCtx } from './context.js';
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
import { loadConfig } from './lib/config.js';
import { startYoutubeSync } from './site/youtube.js';
import { startFeedSync } from './feed/feed.js';
async function main() {
const config = loadConfig();
@@ -21,6 +23,8 @@ async function main() {
const app = createApp(ctx);
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
const stopHeartbeats = startHeartbeats(ctx);
const stopYoutube = startYoutubeSync(ctx);
const stopFeed = startFeedSync(ctx);
connectFromEnv(ctx).then((r) => {
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
@@ -28,6 +32,8 @@ async function main() {
const stop = async () => {
stopHeartbeats();
stopYoutube();
stopFeed();
server.close();
await db.$disconnect();
process.exit(0);
+67 -5
View File
@@ -27,6 +27,37 @@ export class LinkError extends Error {
/** The products the Website links to. */
const LINKABLE = new Set(['accounts', 'events', 'app']);
const NONCE_KEEP_MS = 60 * 60 * 1000;
const REFRESH_EVERY_MS = 60 * 1000;
const SIGN_IN_TRY_EVERY_MS = 15 * 1000;
const refreshes = new WeakMap<Ctx, { at: number; run: Promise<unknown> }>();
/**
* 1.0.2: a fresh list of the church's products from the Hub (a heartbeat), at most once a minute,
* so a message from an unknown install can't make the Website call the Hub more often than that.
* Several callers inside that minute share one heartbeat. Never throws.
*/
async function refreshList(ctx: Ctx): Promise<void> {
const now = ctx.now().getTime();
let r = refreshes.get(ctx);
if (!r || now - r.at >= REFRESH_EVERY_MS) {
// Imported here: hub/client.ts imports this file (it links to Accounts after each heartbeat).
r = { at: now, run: import('../hub/client.js').then((m) => m.heartbeat(ctx)).catch((e) => console.warn('[links] Asking the Hub for a fresh list failed:', (e as Error).message)) };
refreshes.set(ctx, r);
}
await r.run;
}
/**
* 1.0.2: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat), the Website asks the Hub for a fresh list and looks again.
*/
async function listedOrRefreshed(ctx: Ctx, installId: string) {
const found = await listedProduct(ctx, installId);
if (found) return found;
await refreshList(ctx);
return listedProduct(ctx, installId);
}
type Actor = { id: string | null; role: string };
@@ -61,8 +92,8 @@ const logLink = (ctx: Ctx, action: string, link: { installId: string; product: s
/** 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 sibling = await listedOrRefreshed(ctx, installId);
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self(ctx);
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
@@ -93,9 +124,9 @@ export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Pro
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);
const sibling = await listedOrRefreshed(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);
throw new LinkError('The Hub doesn\'t list that install for this church (the Website asks it again at most once a minute).', '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);
@@ -146,7 +177,20 @@ export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request):
* 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'> {
export function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
// 1.0.2: one connect at a time (a heartbeat and a sign-in can both try): two at once would each
// send Accounts a different secret, and the one each side kept last might not be the same.
let run = connecting.get(ctx);
if (!run) {
run = connectAccountsOnce(ctx).finally(() => connecting.delete(ctx));
connecting.set(ctx, run);
}
return run;
}
const connecting = new WeakMap<Ctx, Promise<'connected' | 'skipped' | 'failed'>>();
async function connectAccountsOnce(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';
@@ -158,3 +202,21 @@ export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | '
return 'failed';
}
}
const signInTries = new WeakMap<Ctx, number>();
/**
* 1.0.2: someone wants to sign in and there's no link to Accounts yet: link now instead of waiting
* for the next heartbeat. If the cached list has no Accounts, the Hub is asked for a fresh one first
* (which links by itself when it lists one). Tried at most every 15 seconds, so visitors opening
* /admin can't make the Website call Accounts or the Hub more often than that.
*/
export async function linkAccountsNow(ctx: Ctx): Promise<void> {
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return;
const now = ctx.now().getTime();
const last = signInTries.get(ctx);
if (last !== undefined && now - last < SIGN_IN_TRY_EVERY_MS) return;
signInTries.set(ctx, now);
if (!(await linkedProducts(ctx)).some((p) => p.product === 'accounts')) await refreshList(ctx);
await connectAccountsIfListed(ctx);
}
+79 -5
View File
@@ -1,20 +1,30 @@
/**
* 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 }`.
* What the church's other products call (`crosscode.link/1` and friends), as Cross Events'
* cross-product routes. Errors use the link protocol's `{ code, message }`.
*
* POST /links/v1/connect, /disconnect a sibling connects or disconnects
* GET /feed/v1/events?updatedSince= the Website's events (crosscode.event-feed/1), public
* POST /feed/v1/changed a sibling's events changed: fetch them now (signed)
* POST /church/v1/changed Accounts: the church profile changed (signed)
*/
import express from 'express';
import { LINK_PATHS } from '@crosscode/contracts';
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS } from '@crosscode/contracts';
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
import type { Ctx } from '../context.js';
import { churchChanged } from '../church/profile.js';
import { buildFeed, publishOn, syncLink } from '../feed/feed.js';
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
export function linksRouter(ctx: Ctx) {
const r = express.Router();
const json = express.json({ limit: '32kb' });
const say = (res: express.Response, status: number, code: string, message: string) => res.status(status).json({ code, message });
const fail = (res: express.Response, e: unknown) => {
if (e instanceof LinkError) return res.status(e.status).json({ code: e.code, message: e.message });
if (e instanceof LinkError) return say(res, e.status, e.code, e.message);
console.error('[links]', e);
return res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong.' });
return say(res, 500, 'INTERNAL', 'Something went wrong.');
};
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
try {
res.json(await acceptConnect(ctx, req.body, req));
@@ -30,5 +40,69 @@ export function linksRouter(ctx: Ctx) {
fail(res, e);
}
});
r.get(FEED_PATHS.events.replace(/^\/api/, ''), async (req, res) => {
try {
if (!(await publishOn(ctx))) return say(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events.');
if (!(await ctx.settings.get('hub_install_id'))) return say(res, 503, 'FEED_UNAVAILABLE', 'This site isn\'t connected to the Hub yet, so it has no feed.');
const raw = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null;
const since = raw ? new Date(raw) : null;
if (raw && (!since || !Number.isFinite(since.getTime()))) return say(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
res.set('Cache-Control', 'no-store');
return res.json(await buildFeed(ctx, since));
} catch (e) {
return fail(res, e);
}
});
/** A signed message from a linked sibling: its link, or the reason it's refused. */
async function signedBy(req: express.Request, res: express.Response, accountsOnly = false) {
const sender = String(req.get(LINK_HEADERS.sender) || '');
const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: sender } }) : null;
if (!link || (accountsOnly && link.product !== 'accounts')) {
say(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
return null;
}
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const check = verify({ secret: ctx.secrets.decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody, now: ctx.now() });
if (!check.ok) {
say(res, 401, check.code, 'The signature doesn\'t match this link.');
return null;
}
let body: unknown;
try {
body = JSON.parse(rawBody.toString('utf8'));
} catch {
body = null;
}
return { link, body };
}
const raw = express.raw({ type: () => true, limit: '16kb' });
r.post(FEED_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
try {
const got = await signedBy(req, res);
if (!got) return undefined;
if (!eventChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
// Fetched after answering: the sibling doesn't wait for it.
if (got.link.showEvents) setImmediate(() => { syncLink(ctx, got.link).catch(() => {}); });
return res.status(202).json({ accepted: true, fetching: got.link.showEvents });
} catch (e) {
return fail(res, e);
}
});
r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
try {
const got = await signedBy(req, res, true);
if (!got) return undefined;
if (!churchChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a church.changed message.');
churchChanged(ctx);
return res.status(202).json({ accepted: true });
} catch (e) {
return fail(res, e);
}
});
return r;
}
+26 -9
View File
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
import type { Ctx } from '../context.js';
import { churchProfile } from '../church/profile.js';
import { buildPalette, type Palette } from './palette.js';
import { buildSnapshot, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { buildSnapshot, imageOf, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
export type SiteEvent = {
@@ -21,6 +21,10 @@ export type SiteEvent = {
image: Image | null;
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
url: string;
/** The Website's own events: their page here is /events/<slug> (`url` may be their outside link). */
slug: string | null;
/** An outside link for more information or signing up (the Website's own events). */
link: string | null;
from: 'website' | 'events' | 'app';
registration: { status: string; priceFromCents: number | null } | null;
};
@@ -44,6 +48,8 @@ type Common = {
palette: Palette;
/** The shared brand style, else what the template suggests (§3). */
style: { fontPairing: string; corners: string };
/** Search engines' verification codes, for the home page's meta tags (§11). */
verification: { google: string | null; bing: string | null };
};
export type SiteContent =
@@ -71,6 +77,15 @@ function brandFor(church: Church | null, template: WebsiteTemplate) {
};
}
/** Where the site serves a YouTube video's thumbnail from (site/thumbnails.ts): visitors never ask YouTube. */
export const thumbnailPath = (videoId: string) => `/api/thumbnails/${videoId}.jpg`;
/** A message's thumbnail on the site: its YouTube video's, served from here; none for Spotify. */
export function messageThumbnail(m: { source: string; mediaUrl: string }) {
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
return yt ? thumbnailPath(yt) : null;
}
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
export function youtubeId(url: string): string | null {
try {
@@ -98,7 +113,7 @@ async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
source: m.source === 'spotify' ? 'spotify' : 'youtube',
embedUrl: yt ? `https://www.youtube-nocookie.com/embed/${yt}?autoplay=1` : spotifyEmbed(m.mediaUrl),
url: m.mediaUrl,
thumbnail: m.thumbnailUrl ?? (yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null),
thumbnail: messageThumbnail(m),
};
});
}
@@ -112,18 +127,18 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
]);
const image = (id: string | null) => {
const m = id ? media.find((x) => x.id === id) : null;
return m ? { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } : null;
return m ? imageOf(m) : null;
};
const own: SiteEvent[] = simple.map((e) => ({
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, from: 'website', registration: null,
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
}));
const copies: SiteEvent[] = imported.flatMap((row) => {
const e = row.data as unknown as CrosscodeEvent;
if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return [];
return [{
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null,
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, from: e.origin.product,
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, slug: null, link: null, from: e.origin.product,
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
} satisfies SiteEvent];
});
@@ -137,17 +152,19 @@ export async function siteContent(ctx: Ctx): Promise<SiteContent> {
}
/** The preview (§4): the working copy as it would look published, whatever was published before. */
export async function previewContent(ctx: Ctx): Promise<SiteContent> {
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx)]);
export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<SiteContent> {
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx, opts)]);
return contentFrom(ctx, church, { number: 0, publishedAt: ctx.now(), snapshot });
}
async function contentFrom(ctx: Ctx, church: Church | null, published: { number: number; publishedAt: Date; snapshot: Snapshot } | null): Promise<SiteContent> {
const [google, bing] = await Promise.all([ctx.settings.get('google_verification'), ctx.settings.get('bing_verification')]);
const verification = { google: google || null, bing: bing || null };
if (!published) {
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
return {
mode: 'coming-soon', template, church, ...brandFor(church, template),
mode: 'coming-soon', template, church, ...brandFor(church, template), verification,
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
};
}
@@ -158,5 +175,5 @@ async function contentFrom(ctx: Ctx, church: Church | null, published: { number:
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
}));
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), messages, events };
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), verification, messages, events };
}
+36 -7
View File
@@ -11,11 +11,14 @@ import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { audit } from '../lib/audit.js';
import { parseSectionData } from './sections.js';
import { defaultDesign, isVariant, SECTION_TYPES, type SectionType, type SiteDesign } from './variants.js';
import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionType, type SiteDesign } from './variants.js';
export const SNAPSHOT_VERSION = 1;
export type Image = { url: string; alt: string; width: number | null; height: number | null };
/** An image to show: the photo, and its responsive sizes as `srcset`s when it has them (§3). */
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
@@ -41,12 +44,26 @@ export type Snapshot = {
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
/** Every image the sections refer to, by media id. */
media: Record<string, Image>;
/** Earlier page addresses (without the /) and the path each page has now: a permanent redirect. */
redirects: Record<string, string>;
/** The working copy's rows at publish time: Restore and Discard copy from here (§4). */
source: Source;
};
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
/** A media row as an Image, with `srcset`s from its sizes and the photo itself as the widest. */
export function imageOf(m: MediaRow): Image {
const img: Image = { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height };
const sizes = Array.isArray(m.sizes) ? (m.sizes as { w: number; webp: string; jpg: string }[]) : [];
if (sizes.length && m.width) {
const dir = m.filename.includes('/') ? m.filename.slice(0, m.filename.lastIndexOf('/') + 1) : '';
const set = (key: 'webp' | 'jpg') => [...sizes.map((x) => `${mediaUrl(dir + x[key])} ${x.w}w`), `${img.url} ${m.width}w`].join(', ');
img.srcset = { webp: set('webp'), jpg: set('jpg') };
}
return img;
}
/** The design as saved, made safe: an unknown template, variant or section falls back to the default. */
export function cleanDesign(saved: { template: string; variants: unknown; home: unknown; style: unknown } | null): SiteDesign {
const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage';
@@ -102,13 +119,24 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
}
/** The working copy as a snapshot (what Publish saves, and what the preview shows). */
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
const [w, media] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany()]);
return snapshotFrom(toSource(w), media);
export async function buildSnapshot(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<Snapshot> {
const [w, media, history] = await Promise.all([readWorkingCopy(ctx), ctx.db.mediaAsset.findMany(), ctx.db.slugHistory.findMany()]);
const source = toSource(w);
// "Choose your template" (ROADMAP-v3 §6): the church's own content in another template, as a
// switch would make it, without saving anything.
if (opts.asTemplate) source.design = switchTemplate(cleanDesign(source.design), opts.asTemplate).design;
const snap = snapshotFrom(source, media);
const pathOf = new Map(w.pages.map((p) => [p.id, p.kind === 'home' ? '/' : `/${p.slug}`]));
const live = new Set(w.pages.map((p) => p.slug));
for (const h of history) {
const to = pathOf.get(h.pageId);
if (to && !live.has(h.slug)) snap.redirects[h.slug] = to;
}
return snap;
}
export function snapshotFrom(source: Source, media: { id: string; filename: string; alt: string; width: number | null; height: number | null }[]): Snapshot {
const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image]));
export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
const images = new Map(media.map((m) => [m.id, imageOf(m)]));
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
const used: Record<string, Image> = {};
const collect = (data: unknown) => {
@@ -154,6 +182,7 @@ export function snapshotFrom(source: Source, media: { id: string; filename: stri
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
media: used,
redirects: {},
source,
};
}
@@ -0,0 +1,70 @@
/**
* A message's YouTube thumbnail, served from the site (WEBSITE-1.0-PLAN §7: nothing loads from
* YouTube until a visitor clicks play). The backend fetches `i.ytimg.com/vi/<id>/hqdefault.jpg`
* once and keeps it in `<uploads>/.thumbnails/` (not served from /api/uploads, which denies dot
* folders, and not counted as the church's storage). Only the ids of the site's own messages are
* fetched, so the route is never a proxy for anything else.
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import type { Ctx } from '../context.js';
import { defaultUploadDir } from '../demo/demoChurch.js';
import { youtubeId } from './content.js';
export { thumbnailPath } from './content.js';
export type Fetcher = (url: string) => Promise<Response>;
const ID = /^[A-Za-z0-9_-]{6,20}$/;
const MAX_BYTES = 1024 * 1024;
const cacheDir = (ctx: Ctx) => path.join(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), '.thumbnails');
const defaultFetcher: Fetcher = (url) => fetch(url, { signal: AbortSignal.timeout(10_000) });
/** One fetch per video at a time, however many visitors ask at once. */
const inFlight = new Map<string, Promise<Buffer | null>>();
async function isOurVideo(ctx: Ctx, videoId: string) {
const rows = await ctx.db.message.findMany({ where: { mediaUrl: { contains: videoId } }, select: { mediaUrl: true, source: true }, take: 5 });
return rows.some((m) => m.source !== 'spotify' && youtubeId(m.mediaUrl) === videoId);
}
async function download(fetcher: Fetcher, videoId: string): Promise<Buffer | null> {
try {
const res = await fetcher(`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`);
if (!res.ok || !/^image\/jpe?g/.test(res.headers.get('content-type') ?? '')) return null;
const body = Buffer.from(await res.arrayBuffer());
// A JPEG by its bytes, and a sensible size.
if (body.length > MAX_BYTES || body.length < 3 || body[0] !== 0xff || body[1] !== 0xd8 || body[2] !== 0xff) return null;
return body;
} catch {
return null;
}
}
/** The thumbnail's bytes, from the cache or YouTube; null when it isn't one of the site's videos or YouTube has none. */
export async function thumbnail(ctx: Ctx, videoId: string, fetcher: Fetcher = ctx.fetch ?? defaultFetcher): Promise<Buffer | null> {
if (!ID.test(videoId)) return null;
const file = path.join(cacheDir(ctx), `${videoId}.jpg`);
try {
return await fs.readFile(file);
} catch {
// Not cached yet.
}
if (!(await isOurVideo(ctx, videoId))) return null;
let pending = inFlight.get(videoId);
if (!pending) {
pending = (async () => {
const body = await download(fetcher, videoId);
if (body) {
await fs.mkdir(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
await fs.writeFile(tmp, body);
await fs.rename(tmp, file);
}
return body;
})().finally(() => inFlight.delete(videoId));
inFlight.set(videoId, pending);
}
return pending;
}
+111
View File
@@ -0,0 +1,111 @@
/**
* Messages from YouTube, automatically (WEBSITE-1.0-PLAN §7, decision 7): the church's channel or a
* playlist, read from YouTube's public feed (no API key) every hour. Each new video becomes a
* message, live at once (decision 9); admins add the speaker, series and passage afterwards, or hide
* one. A video already here (by its id, however it came in) is never added twice.
*/
import type { Ctx } from '../context.js';
import { ApiError } from '../http.js';
export type YoutubeSource = { kind: 'channel' | 'playlist'; id: string };
/** A channel id (UC…), a channel or playlist address, or a playlist id (PL…, UU…, OL…). */
export function parseSource(input: string): YoutubeSource | null {
const v = input.trim();
const channel = /(?:^|\/channel\/)(UC[\w-]{22})(?:[/?#]|$)/.exec(v);
if (channel) return { kind: 'channel', id: channel[1]! };
const list = /[?&]list=([\w-]{10,64})/.exec(v) ?? /^((?:PL|UU|OL|FL)[\w-]{10,62})$/.exec(v);
if (list) return { kind: 'playlist', id: list[1]! };
return null;
}
export const feedUrl = (s: YoutubeSource) => `https://www.youtube.com/feeds/videos.xml?${s.kind === 'channel' ? 'channel_id' : 'playlist_id'}=${encodeURIComponent(s.id)}`;
export type FeedVideo = { videoId: string; title: string; published: Date; thumbnail: string | null };
const unescape = (s: string) => s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&amp;/g, '&');
/** The videos in a YouTube Atom feed. Entries without an id, title or date are left out. */
export function parseFeed(xml: string): FeedVideo[] {
const out: FeedVideo[] = [];
for (const m of xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)) {
const e = m[1]!;
const videoId = /<yt:videoId>([\w-]{6,20})<\/yt:videoId>/.exec(e)?.[1];
const title = /<title>([\s\S]*?)<\/title>/.exec(e)?.[1];
const published = /<published>([^<]+)<\/published>/.exec(e)?.[1];
const thumbnail = /<media:thumbnail url="([^"]+)"/.exec(e)?.[1] ?? null;
const date = published ? new Date(published) : null;
if (!videoId || !title || !date || Number.isNaN(date.getTime())) continue;
out.push({ videoId, title: unescape(title.trim()).slice(0, 500), published: date, thumbnail: thumbnail && thumbnail.startsWith('https://') ? thumbnail : null });
}
return out;
}
export async function getSource(ctx: Ctx): Promise<YoutubeSource | null> {
return ctx.settings.json<YoutubeSource | null>('youtube_source', null);
}
export async function setSource(ctx: Ctx, input: string | null): Promise<YoutubeSource | null> {
if (!input?.trim()) {
await ctx.settings.set('youtube_source', null);
return null;
}
const s = parseSource(input);
if (!s) throw new ApiError(400, 'VALIDATION', 'That isn\'t a YouTube channel id (UC…) or playlist address.', { youtube: 'A channel id (UC…) or a playlist link' });
await ctx.settings.set('youtube_source', JSON.stringify(s));
return s;
}
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'message';
export async function uniqueSlug(ctx: Ctx, title: string, model: 'message' | 'simpleEvent', except?: string) {
const base = slugify(title);
for (let n = 1; ; n++) {
const slug = n === 1 ? base : `${base}-${n}`;
const taken = model === 'message'
? await ctx.db.message.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } })
: await ctx.db.simpleEvent.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
if (!taken) return slug;
}
}
type Fetcher = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>;
/** The hourly job: new videos become messages. Returns how many were added. */
export async function syncYoutube(ctx: Ctx, fetcher: Fetcher = (u) => fetch(u, { signal: AbortSignal.timeout(15000), headers: { accept: 'application/atom+xml' } })) {
const source = await getSource(ctx);
if (!source) return { added: 0, skipped: 'no source' };
let videos: FeedVideo[];
try {
const res = await fetcher(feedUrl(source));
if (!res.ok) throw new Error(`YouTube answered ${res.status}`);
videos = parseFeed(await res.text());
} catch (e) {
await ctx.settings.set('youtube_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 300));
return { added: 0, error: (e as Error).message };
}
let added = 0;
for (const v of videos) {
if (await ctx.db.message.findUnique({ where: { externalId: v.videoId } })) continue;
await ctx.db.message.create({
data: {
slug: await uniqueSlug(ctx, v.title, 'message'), title: v.title, date: v.published, source: 'youtube_feed',
mediaUrl: `https://www.youtube.com/watch?v=${v.videoId}`, externalId: v.videoId, thumbnailUrl: v.thumbnail, publishedAt: ctx.now(),
},
});
added++;
}
await ctx.settings.setMany({ youtube_last_sync_at: ctx.now().toISOString(), youtube_last_error: null });
return { added };
}
/** Every hour while the site runs (pg-boss comes with the other jobs). */
export function startYoutubeSync(ctx: Ctx): () => void {
if (!ctx.config.jobsEnabled) return () => {};
const run = () => syncYoutube(ctx).catch((e) => console.warn('[youtube]', (e as Error).message));
const first = setTimeout(run, 30_000);
const timer = setInterval(run, 60 * 60 * 1000);
first.unref?.();
timer.unref?.();
return () => { clearTimeout(first); clearInterval(timer); };
}
+38 -9
View File
@@ -4,6 +4,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import request from 'supertest';
import sharp from 'sharp';
import { loadDemo } from '../src/demo/demoChurch.js';
import { hashToken } from '../src/lib/crypto.js';
import { dimensions, sniff } from '../src/admin/media.js';
@@ -181,17 +182,45 @@ describe('uploads and storage (§10, decision 12)', () => {
assert.equal(sniff(Buffer.from('<svg>')), null);
});
it('stores an upload, refuses what isn\'t a photo, and stops when storage is full', async () => {
const { as, db, dir } = await signedIn('editor');
const up = await as.upload('/media?alt=The%20hall', png);
it('keeps a photo upright and without its location, in responsive sizes; refuses what isn\'t one', async () => {
const { as, dir, app } = await signedIn('editor');
// A 2000 × 1200 phone photo with its GPS position in the metadata.
const photo = await sharp({ create: { width: 2000, height: 1200, channels: 3, background: '#1d5c63' } })
.jpeg().withExifMerge({ IFD3: { GPSLatitudeRef: 'S', GPSLatitude: '25/1 44/1 46/1' } }).toBuffer();
assert.ok((await sharp(photo).metadata()).exif, 'the test photo has EXIF');
const up = await as.upload('/media?alt=The%20hall', photo);
assert.equal(up.status, 200);
assert.equal(up.body.width, 640);
assert.ok(fs.existsSync(path.join(dir, up.body.filename)));
const notPhoto = await as.upload('/media', Buffer.from('<svg onload=alert(1)>'));
assert.equal(notPhoto.status, 415);
// Full: the media library already holds the included 5 GB.
assert.equal(up.body.width, 2000);
assert.deepEqual(up.body.sizes.map((x: { w: number }) => x.w), [480, 960, 1600]);
const file = path.join(dir, up.body.filename);
assert.equal((await sharp(fs.readFileSync(file)).metadata()).exif, undefined, 'no metadata kept');
const files = fs.readdirSync(path.dirname(file));
assert.equal(files.length, 7, 'the photo and 3 sizes in WebP and JPEG');
const total = files.reduce((t, n) => t + fs.statSync(path.join(path.dirname(file), n)).size, 0);
assert.equal(up.body.bytes, total, 'every file counts towards storage');
// The site gets srcsets.
const about = (await as.get('/pages')).body.find((p: { kind: string }) => p.kind === 'about').id;
await as.put(`/pages/${about}`, { imageId: up.body.id });
await as.post('/publish');
const content = (await request(app).get('/api/v1/site/content')).body;
const img = content.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').image;
assert.match(img.srcset.webp, /-480\.webp 480w, .*-960\.webp 960w, .*-1600\.webp 1600w, .*\.jpg 2000w$/);
const big = await sharp({ create: { width: 4000, height: 3000, channels: 3, background: '#e0a458' } }).png().toBuffer();
const b = await as.upload('/media', big);
assert.equal(b.body.width, 2400, 'kept at most 2400 wide');
assert.equal(b.body.height, 1800);
assert.equal((await as.upload('/media', Buffer.from('<svg onload=alert(1)>'))).status, 415);
assert.equal((await as.upload('/media', png)).status, 415, 'a PNG header with nothing behind it');
});
it('stops uploads when storage is full', async () => {
const { as, db } = await signedIn('editor');
const photo = await sharp({ create: { width: 800, height: 600, channels: 3, background: '#ffffff' } }).jpeg().toBuffer();
// The media library already holds the included 5 GB.
await db.mediaAsset.create({ data: { filename: 'big.jpg', mime: 'image/jpeg', bytes: 5 * 1024 ** 3 } });
const full = await as.upload('/media', png);
const full = await as.upload('/media', photo);
assert.equal(full.status, 409);
assert.equal(full.body.error.code, 'STORAGE_FULL');
assert.equal((await as.get('/media')).body.storage.full, true);
@@ -0,0 +1,87 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { previewContent, siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { harness, SITE } from './support/harness.js';
async function site() {
const h = await harness({ linked: false });
const people = { ann: '00000000-0000-4000-8000-00000000000a', ben: '00000000-0000-4000-8000-00000000000b', lee: '00000000-0000-4000-8000-00000000000c' };
const kids = await h.db.ministry.create({ data: { slug: 'kids', name: 'Kids' } });
const youth = await h.db.ministry.create({ data: { slug: 'youth', name: 'Youth' } });
await h.db.websiteUser.create({ data: { id: people.ann, name: 'Ann', email: 'ann@hope.test', role: 'editor' } });
await h.db.websiteUser.create({ data: { id: people.ben, name: 'Ben', email: 'ben@hope.test', role: 'editor' } });
await h.db.websiteUser.create({ data: { id: people.lee, name: 'Lee', email: 'lee@hope.test', role: 'ministry_leader', ministryId: kids.id } });
for (const [k, id] of Object.entries(people)) await h.db.session.create({ data: { tokenHash: hashToken(k), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const as = (who: keyof typeof people) => (m: 'get' | 'post' | 'put', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', `ccw_session=${who}`).set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, as, kids, youth };
}
describe('two editors at once (§4)', () => {
it("doesn't overwrite someone else's save, and says who", async () => {
const { as, db } = await site();
const page = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About' } });
const loaded = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt;
await new Promise((r) => setTimeout(r, 5));
assert.equal((await as('ben')('put', `/pages/${page.id}`, { title: "Ben's title", ifUpdatedAt: loaded })).status, 200);
const ann = await as('ann')('put', `/pages/${page.id}`, { title: "Ann's title", ifUpdatedAt: loaded });
assert.equal(ann.status, 409);
assert.match(ann.body.error.message, /^Ben changed this/);
assert.equal((await as('ann')('get', `/pages/${page.id}`)).body.title, "Ben's title");
// Her own earlier save never blocks her.
const fresh = (await as('ann')('get', `/pages/${page.id}`)).body.updatedAt;
assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'One', ifUpdatedAt: fresh })).status, 200);
assert.equal((await as('ann')('put', `/pages/${page.id}`, { title: 'Two', ifUpdatedAt: fresh })).status, 200);
});
});
describe("a Ministry leader's events (§10)", () => {
it('adds and changes their own ministry\'s events only, and an Editor publishes them', async () => {
const { as, kids, youth } = await site();
const startsAt = new Date(Date.now() + 864e5).toISOString();
assert.equal((await as('lee')('post', '/events', { title: 'Youth night', startsAt, ministryId: youth.id })).status, 403);
assert.equal((await as('lee')('post', '/events', { title: 'No ministry', startsAt })).status, 403);
const mine = await as('lee')('post', '/events', { title: 'Kids party', startsAt, ministryId: kids.id });
assert.equal(mine.status, 200);
assert.equal((await as('lee')('put', `/events/${mine.body.id}`, { title: 'Kids party!', startsAt, ministryId: kids.id })).status, 200);
assert.equal((await as('lee')('post', `/events/${mine.body.id}/state`, { published: true })).status, 403);
const other = await as('ann')('post', '/events', { title: 'Picnic', startsAt });
assert.equal((await as('lee')('put', `/events/${other.body.id}`, { title: 'Mine now', startsAt, ministryId: kids.id })).status, 403);
assert.equal((await as('ann')('post', `/events/${mine.body.id}/state`, { published: true })).status, 200);
});
});
describe('choosing a template with the church\'s own content', () => {
it('previews the content in another template without saving anything', async () => {
const { ctx, db, as, app } = await site();
await db.siteDesign.create({ data: { id: 1, template: 'heritage', variants: {}, home: [], style: {} } });
const c = await previewContent(ctx, { asTemplate: 'bold' });
assert.equal(c.mode === 'published' && c.snapshot.design.template, 'bold');
assert.equal((await as('ann')('get', '/design')).body.design.template, 'heritage', 'nothing saved');
const viaHeader = await request(app).get('/api/v1/site/preview').set('Cookie', 'ccw_session=ann').set('x-preview-template', 'clean');
assert.equal(viaHeader.body.snapshot.design.template, 'clean');
assert.equal(viaHeader.body.preview.canPublish, false, 'no publishing from a try-on');
});
});
describe('an address that changed (§6)', () => {
it('sends the old address on to the new one once published', async () => {
const { ctx, db, as } = await site();
const page = await db.page.create({ data: { kind: 'custom', slug: 'youth-camp', title: 'Youth camp' } });
await as('ann')('put', `/pages/${page.id}`, { slug: 'camp' });
await as('ann')('put', `/pages/${page.id}`, { slug: 'summer-camp' });
await publish(ctx, { id: 'x', role: 'system' });
const c = await siteContent(ctx);
assert.deepEqual(c.mode === 'published' && c.snapshot.redirects, { 'youth-camp': '/summer-camp', camp: '/summer-camp' });
// A new page taking an old address wins over its redirect.
await db.page.create({ data: { kind: 'custom', slug: 'camp', title: 'Camp info' } });
await publish(ctx, { id: 'x', role: 'system' });
const after = await siteContent(ctx);
assert.deepEqual(after.mode === 'published' && after.snapshot.redirects, { 'youth-camp': '/summer-camp' });
});
});
+175
View File
@@ -0,0 +1,175 @@
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 { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventFeedSchema, eventSchema } from '@crosscode/contracts';
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
import { hashToken } from '../src/lib/crypto.js';
import { buildFeed, syncLink } from '../src/feed/feed.js';
import { siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { harness, INSTALL_ID, SITE } from './support/harness.js';
const EVENTS_ID = '5b6c7d8e-9f0a-4b1c-8d2e-3f4a5b6c7d8e';
const SECRET = 'events-link-secret-0123456789abcdef';
/** A Cross Events event, as its feed sends it. */
function ev(id: string, title: string, inDays: number, over: Record<string, unknown> = {}) {
const start = new Date(Date.now() + inDays * 864e5);
return {
schema: EVENT_SCHEMA, id, origin: { product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${id.slice(0, 4)}` },
status: 'published', updatedAt: new Date().toISOString(), title, summary: null, description: null, imageUrl: null, timezone: 'Africa/Johannesburg',
startsAt: start.toISOString(), endsAt: new Date(start.getTime() + 3600e3).toISOString(), allDay: false, sessions: [], location: { name: 'The hall', address: null, onlineUrl: null },
campus: null, series: null, tags: [], registration: { mode: 'origin', url: `https://events.hope.test/events/${id.slice(0, 4)}`, status: 'open', opensAt: null, closesAt: null, priceFrom: { amountCents: 45000, currency: 'ZAR' } },
...over,
};
}
/** A Cross Events site: serves whatever feed the test sets, and records what it's told. */
async function fakeEvents() {
const state = { feed: null as unknown, status: 200, asked: [] as string[], told: [] as { headers: http.IncomingHttpHeaders; body: string }[] };
const app = express();
app.get('/api/feed/v1/events', (req, res) => { state.asked.push(req.url); res.status(state.status).json(state.feed); });
app.post('/api/feed/v1/changed', express.text({ type: () => true }), (req, res) => { state.told.push({ headers: req.headers, body: req.body }); res.status(202).json({ accepted: true }); });
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, state };
}
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
async function site() {
const h = await harness({ env: { LINKS_ALLOW_PRIVATE: 'true' } });
const events = await fakeEvents();
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: events.url, publicKey: 'x', secret: h.ctx.secrets.encrypt(SECRET), connectedAt: new Date() } });
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000001', name: 'O', email: 'o@hope.test', role: 'owner' } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000001', expiresAt: new Date(Date.now() + 864e5) } });
await publish(h.ctx, { id: 'x', role: 'system' });
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
const link = async () => (await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } })) as unknown as Parameters<typeof syncLink>[1];
return { ...h, events, go, link };
}
describe('publishing the Website\'s events (Publish my events)', () => {
it('serves its published simple events as crosscode.event/1, removed ones as deleted', async () => {
const { go, app } = await site();
const start = new Date(Date.now() + 5 * 864e5).toISOString();
const a = (await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/p' })).body;
const b = (await go('post', '/events', { title: 'Carols', startsAt: start })).body;
await go('post', `/events/${a.id}/state`, { published: true });
await go('post', `/events/${b.id}/state`, { published: true });
const feed = (await request(app).get('/api/feed/v1/events')).body;
assert.ok(eventFeedSchema.safeParse(feed).success);
assert.equal(feed.events.length, 2);
const picnic = feed.events.find((e: { title: string }) => e.title === 'Picnic');
assert.ok(eventSchema.safeParse(picnic).success);
assert.deepEqual(picnic.origin, { product: 'website', installId: INSTALL_ID, url: `${SITE}/events/picnic` });
assert.deepEqual([picnic.registration.mode, picnic.registration.url], ['external', 'https://forms.example/p']);
const before = new Date().toISOString();
await go('post', `/events/${b.id}/state`, { published: false });
const since = (await request(app).get(`/api/feed/v1/events?updatedSince=${encodeURIComponent(before)}`)).body;
assert.deepEqual(since.deleted.map((d: { id: string }) => d.id), [b.id]);
assert.equal(since.events.length, 0, 'nothing else changed since');
assert.equal((await request(app).get('/api/feed/v1/events?updatedSince=nonsense')).status, 400);
await go('put', '/feed', { publish: false });
assert.equal((await request(app).get('/api/feed/v1/events')).status, 404);
});
it('tells the church\'s Events, signed, when one of its events changes', async () => {
const { go, events } = await site();
const e = (await go('post', '/events', { title: 'Picnic', startsAt: new Date(Date.now() + 864e5).toISOString() })).body;
await go('post', `/events/${e.id}/state`, { published: true });
await new Promise((r) => setTimeout(r, 200));
const told = events.state.told.at(-1)!;
assert.equal(told.headers[LINK_HEADERS.sender], INSTALL_ID);
assert.deepEqual(JSON.parse(told.body).eventIds, [e.id]);
});
});
describe('showing events from Cross Events (Show events from)', () => {
it('imports only its own, valid events; they show on the site and link back to Events', async () => {
const { ctx, events, link, db } = await site();
events.state.feed = {
schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [],
events: [
ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10),
ev('7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a', 'From someone else', 4, { origin: { product: 'events', installId: '00000000-0000-4000-8000-0000000000ff', url: 'https://other.test/e' } }),
{ ...ev('8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b', 'Broken', 3), startsAt: 'not a date' },
],
};
const r = await syncLink(ctx, await link());
assert.deepEqual([r.ok, r.imported, r.rejected], [true, 1, 1]);
const c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events.length, 1);
if (c.mode === 'published') {
assert.equal(c.events[0]!.title, 'Youth camp');
assert.equal(c.events[0]!.url, 'https://events.hope.test/events/6c7d');
assert.deepEqual(c.events[0]!.registration, { status: 'open', priceFromCents: 45000 });
}
assert.match(String((await db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.lastSyncError), /1 event\(s\) skipped/);
});
it('asks only for what changed next time, drops deleted ones, and keeps the last good copy when Events is down', async () => {
const { ctx, events, link, db } = await site();
const id = '6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f';
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev(id, 'Youth camp', 10)] };
await syncLink(ctx, await link());
events.state.status = 503;
const down = await syncLink(ctx, await link());
assert.equal(down.ok, false);
assert.equal(await db.importedEvent.count(), 1, 'the last good copy stays');
assert.match(events.state.asked.at(-1)!, /updatedSince=/);
events.state.status = 200;
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [{ id, deletedAt: new Date().toISOString() }], events: [] };
await syncLink(ctx, await link());
assert.equal(await db.importedEvent.count(), 0);
});
it('switching Show events off removes its events; a signed event.changed fetches at once', async () => {
const { ctx, events, link, db, go, app } = await site();
events.state.feed = { schema: EVENT_FEED_SCHEMA, generatedAt: new Date().toISOString(), deleted: [], events: [ev('6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f', 'Youth camp', 10)] };
await syncLink(ctx, await link());
await go('put', `/links/${EVENTS_ID}`, { showEvents: false });
assert.equal(await db.importedEvent.count(), 0);
await go('put', `/links/${EVENTS_ID}`, { showEvents: true });
assert.equal(await db.importedEvent.count(), 1);
const body = JSON.stringify({ schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [] });
const asked = events.state.asked.length;
const ok = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: SECRET, rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal(ok.status, 202);
await new Promise((r) => setTimeout(r, 200));
assert.equal(events.state.asked.length, asked + 1);
const forged = await request(app).post('/api/feed/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: EVENTS_ID, secret: 'wrong-secret-0123456789abcdefghij', rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal(forged.status, 401);
const links = (await go('get', '/links')).body;
assert.equal(links.products.find((p: { product: string }) => p.product === 'events').events, 1);
});
it('takes church.changed only from Accounts, signed', async () => {
const { app, db, ctx } = await site();
const accounts = (await db.productLink.findFirst({ where: { product: 'accounts' } }))!;
const body = JSON.stringify({ schema: 'crosscode.church/1', type: 'church.changed', occurredAt: new Date().toISOString(), updatedAt: new Date().toISOString() });
const send = (sender: string, secret: string) => request(app).post('/api/church/v1/changed').set(signedHeaders(LINK_HEADERS, { senderId: sender, secret, rawBody: body })).set('Content-Type', 'application/json').send(body);
assert.equal((await send(String(accounts.installId), ctx.secrets.decrypt(String(accounts.secret)))).status, 202);
assert.equal((await send(EVENTS_ID, SECRET)).status, 404, 'Events isn\'t Accounts');
});
});
describe('the feed builder', () => {
it('leaves out events that ended over 30 days ago', async () => {
const { ctx, db } = await site();
await db.simpleEvent.create({ data: { slug: 'old', title: 'Old', startsAt: new Date(Date.now() - 40 * 864e5), publishedAt: new Date() } });
assert.equal((await buildFeed(ctx, null)).events.length, 0);
});
});
@@ -0,0 +1,111 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { siteContent } from '../src/site/content.js';
import { publish } from '../src/site/snapshot.js';
import { parseFeed, parseSource, syncYoutube } from '../src/site/youtube.js';
import { harness, SITE } from './support/harness.js';
const FEED = `<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:yt="http://www.youtube.com/xml/schemas/2015" xmlns:media="http://search.yahoo.com/mrss/" xmlns="http://www.w3.org/2005/Atom">
<title>Hope Family Church</title>
<entry>
<id>yt:video:abcDEF12345</id>
<yt:videoId>abcDEF12345</yt:videoId>
<title>Hope &amp; joy | Sunday 23 Nov</title>
<published>2026-11-23T08:00:00+00:00</published>
<media:group><media:thumbnail url="https://i1.ytimg.com/vi/abcDEF12345/hqdefault.jpg" width="480" height="360"/></media:group>
</entry>
<entry>
<yt:videoId>zzzYYY98765</yt:videoId>
<title>Bread for the road</title>
<published>2026-11-16T08:00:00+00:00</published>
</entry>
<entry><title>No id</title><published>2026-11-01T08:00:00+00:00</published></entry>
</feed>`;
async function signedIn() {
const h = await harness({ linked: false });
await h.db.websiteUser.create({ data: { id: '00000000-0000-4000-8000-000000000003', name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: '00000000-0000-4000-8000-000000000003', expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post' | 'put' | 'delete', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
await publish(h.ctx, { id: 'x', role: 'system' });
return { ...h, go };
}
describe('messages from YouTube (§7)', () => {
it('reads a channel id, a channel address or a playlist', () => {
assert.deepEqual(parseSource('UCaBcDeFgHiJkLmNoPqRsTuV'), { kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' });
assert.deepEqual(parseSource('https://www.youtube.com/channel/UCaBcDeFgHiJkLmNoPqRsTuV/videos'), { kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' });
assert.deepEqual(parseSource('https://www.youtube.com/playlist?list=PLabcdefghij123'), { kind: 'playlist', id: 'PLabcdefghij123' });
assert.equal(parseSource('https://www.youtube.com/@hopefamily'), null);
});
it('parses the feed, leaving out entries it can\'t use', () => {
const v = parseFeed(FEED);
assert.equal(v.length, 2);
assert.equal(v[0]!.title, 'Hope & joy | Sunday 23 Nov');
assert.equal(v[0]!.thumbnail, 'https://i1.ytimg.com/vi/abcDEF12345/hqdefault.jpg');
});
it('adds new videos as live messages, once, and says when YouTube can\'t be reached', async () => {
const h = await harness({ linked: false });
await h.ctx.settings.set('youtube_source', JSON.stringify({ kind: 'channel', id: 'UCaBcDeFgHiJkLmNoPqRsTuV' }));
let asked = '';
const ok = async (u: string) => { asked = u; return { ok: true, status: 200, text: async () => FEED }; };
assert.deepEqual(await syncYoutube(h.ctx, ok), { added: 2 });
assert.equal(asked, 'https://www.youtube.com/feeds/videos.xml?channel_id=UCaBcDeFgHiJkLmNoPqRsTuV');
assert.deepEqual(await syncYoutube(h.ctx, ok), { added: 0 });
await publish(h.ctx, { id: 'x', role: 'system' });
const c = await siteContent(h.ctx);
assert.equal(c.mode === 'published' && c.messages[0]!.title, 'Hope & joy | Sunday 23 Nov');
const down = await syncYoutube(h.ctx, async () => ({ ok: false, status: 503, text: async () => '' }));
assert.match(String(down.error), /503/);
assert.match(String(await h.ctx.settings.get('youtube_last_error')), /503/);
});
});
describe('messages and events in the admin (decision 9)', () => {
it('adds a message by link, publishes it on its own, and refuses a duplicate or a stranger link', async () => {
const { go, ctx } = await signedIn();
const m = await go('post', '/messages', { title: 'Grace', date: '2026-11-22', mediaUrl: 'https://youtu.be/abcDEF12345', speaker: 'Thandi', series: 'Hope' });
assert.equal(m.status, 200);
let c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.messages.length, 0, 'not live until its own Publish');
await go('post', `/messages/${m.body.id}/publish`, { live: true });
c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.messages[0]!.series, 'Hope');
assert.equal((await go('post', '/messages', { title: 'Again', date: '2026-11-22', mediaUrl: 'https://www.youtube.com/watch?v=abcDEF12345' })).body.error.code, 'DUPLICATE');
assert.equal((await go('post', '/messages', { title: 'X', date: '2026-11-22', mediaUrl: 'https://evil.example/v' })).status, 400);
const spotify = await go('post', '/messages', { title: 'Podcast', date: '2026-11-22', mediaUrl: 'https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk' });
assert.equal(spotify.body.source, 'spotify');
});
it('keeps a feed message from being deleted (it would come back): hide it instead', async () => {
const { go, db } = await signedIn();
const row = await db.message.create({ data: { slug: 'x', title: 'From YouTube', date: new Date(), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abcDEF12345', externalId: 'abcDEF12345' } });
assert.equal((await go('delete', `/messages/${row.id}`)).body.error.code, 'FROM_FEED');
});
it('creates, publishes, cancels and removes a simple event', async () => {
const { go, ctx } = await signedIn();
const start = new Date(Date.now() + 7 * 864e5).toISOString();
const bad = await go('post', '/events', { title: 'Picnic', startsAt: start, endsAt: new Date(Date.now()).toISOString() });
assert.ok(bad.body.error.fields.endsAt);
const e = await go('post', '/events', { title: 'Picnic', startsAt: start, location: 'The park', link: 'https://forms.example/picnic' });
assert.equal(e.status, 200);
assert.equal(e.body.slug, 'picnic');
await go('post', `/events/${e.body.id}/state`, { published: true });
let c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events[0]!.url, 'https://forms.example/picnic');
await go('post', `/events/${e.body.id}/state`, { cancelled: true });
c = await siteContent(ctx);
assert.equal(c.mode === 'published' && c.events.length, 0);
assert.equal((await go('delete', `/events/${e.body.id}`)).status, 200);
assert.equal((await go('get', '/events')).body.length, 0);
});
});
+67 -1
View File
@@ -10,7 +10,7 @@ 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';
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID, SITE } from './support/harness.js';
const accountsKeys = generateEd25519();
const accountsPublic = ed25519PublicToPem(accountsKeys.publicKey);
@@ -88,6 +88,72 @@ describe('linking to the church\'s Accounts', () => {
});
});
/** A Hub answering heartbeats with `list` as the church's products (only what the Website reads). */
async function fakeHub(list: () => unknown[]) {
const calls: string[] = [];
const server = http.createServer((req, res) => {
calls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: list() }));
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, calls };
}
describe('1.0.2: linking right after an install', () => {
it('links to Accounts when someone opens /admin, asking the Hub for a fresh list first', async () => {
let accountsUrl = '';
const hubServer = await fakeHub(() => [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accountsUrl, publicKey: accountsPublic }]);
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true', HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
closers.push(accounts.close);
accountsUrl = accounts.url;
// The Website's cached list has no Accounts yet (it registered before the Hub knew of one).
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(res.status, 303);
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//, 'off to Accounts, not the problem page');
assert.deepEqual(hubServer.calls, ['/api/installs/heartbeat']);
assert.equal(accounts.seen.length, 1, 'one connect, not one from the heartbeat and another from the sign-in');
assert.equal(await h.db.productLink.count({ where: { product: 'accounts' } }), 1);
});
it('tries again at most every 15 seconds while it can\'t link', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const hubServer = await fakeHub(() => []);
const h = await harness({ linked: false, env: { HUB_URL: hubServer.url } });
h.ctx.now = () => clock;
await h.ctx.settings.set('hub_install_secret', 'secret');
const problem = `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`;
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal(hubServer.calls.length, 1);
clock = new Date(clock.getTime() + 61_000);
await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(hubServer.calls.length, 2);
});
it('accepts a connect from a product installed after its last heartbeat (Events, for the event feed)', async () => {
const EVENTS_INSTALL_ID = '4d2e8f3a-9b1c-4d0e-8f7a-6b5c4d3e2f1a';
const eventsKeys = generateEd25519();
const events = { product: 'events', installId: EVENTS_INSTALL_ID, url: 'https://events.hope.test', publicKey: ed25519PublicToPem(eventsKeys.publicKey) };
const hubServer = await fakeHub(() => [events]);
const h = await harness({ env: { HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const m = signLink({
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'events', installId: EVENTS_INSTALL_ID, url: events.url },
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, eventsKeys.privateKeyPem);
const res = await request(h.app).post('/api/links/v1/connect').send(m);
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(hubServer.calls.length, 1);
assert.equal(await h.db.productLink.count({ where: { product: 'events' } }), 1);
});
});
describe('the heartbeat and the export', () => {
it('reports aggregate counts the Hub accepts', async () => {
const h = await harness();
+69
View File
@@ -0,0 +1,69 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { harness, SITE } from './support/harness.js';
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
/** A site linked to Accounts, with an Owner and an Admin signed in (each with their own cookie). */
async function site() {
const h = await harness();
const people: Record<string, { id: string; cookie: string }> = {};
for (const [n, role] of (['owner', 'admin', 'editor'] as Role[]).entries()) {
const id = `00000000-0000-4000-8000-00000000000${n + 1}`;
await h.db.websiteUser.create({ data: { id, name: role, email: `${role}@hope.test`, role } });
await h.db.session.create({ data: { tokenHash: hashToken(`t-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
people[role] = { id, cookie: `ccw_session=t-${role}` };
}
const as = (role: string) => ({
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie),
post: (p: string, b: object) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE).send(b),
put: (p: string, b: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE).send(b),
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', people[role]!.cookie).set('Origin', SITE),
});
return { ...h, people, as };
}
describe('who can use the admin (§10)', () => {
it('adds someone by email through Accounts, who can then sign in with that role', async () => {
const { as, fake, db } = await site();
const r = await as('admin').post('/people', { name: 'New Editor', email: 'New@Hope.test', role: 'editor' });
assert.equal(r.status, 200);
assert.equal(r.body.newAccount, true);
assert.deepEqual(fake.requests[0], { type: 'people.ensure', actor: '00000000-0000-4000-8000-000000000002', name: 'New Editor', email: 'new@hope.test', phone: null, returnUrl: `${SITE}/admin` });
const u = await db.websiteUser.findUnique({ where: { id: r.body.id } });
assert.equal(u!.role, 'editor');
assert.equal((await as('admin').post('/people', { name: 'Again', email: 'new@hope.test', role: 'viewer' })).body.error.code, 'ALREADY_ADDED');
const list = (await as('owner').get('/people')).body;
assert.equal(list.length, 4);
});
it('needs a ministry for a Ministry leader', async () => {
const { as, db } = await site();
assert.equal((await as('admin').post('/people', { name: 'L', email: 'l@hope.test', role: 'ministry_leader' })).status, 400);
const m = await db.ministry.create({ data: { slug: 'kids', name: 'Kids' } });
const r = await as('admin').post('/people', { name: 'L', email: 'l@hope.test', role: 'ministry_leader', ministryId: m.id });
assert.equal(r.status, 200);
assert.equal((await as('admin').get('/people')).body.find((p: { id: string }) => p.id === r.body.id).ministry, 'Kids');
});
it('keeps Owners to Owners, and nobody changes themselves', async () => {
const { as, people } = await site();
assert.equal((await as('admin').post('/people', { name: 'O', email: 'o@hope.test', role: 'owner' })).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('admin').put(`/people/${people.owner!.id}`, { role: 'viewer' })).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('admin').del(`/people/${people.owner!.id}`)).body.error.code, 'OWNERS_ONLY');
assert.equal((await as('owner').put(`/people/${people.owner!.id}`, { role: 'viewer' })).body.error.code, 'SELF');
assert.equal((await as('editor').get('/people')).status, 403);
assert.equal((await as('owner').post('/people', { name: 'Second owner', email: 'o@hope.test', role: 'owner' })).status, 200);
});
it('a lower role takes effect at once; removing someone ends their sessions', async () => {
const { as, people, db } = await site();
assert.equal((await as('owner').put(`/people/${people.editor!.id}`, { role: 'viewer' })).status, 200);
assert.equal(await db.session.count({ where: { userId: people.editor!.id } }), 0);
assert.equal((await as('owner').del(`/people/${people.admin!.id}`)).status, 200);
assert.equal(await db.websiteUser.count({ where: { id: people.admin!.id } }), 0);
assert.equal((await as('admin').get('/people')).status, 401);
});
});
@@ -0,0 +1,70 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { hashToken } from '../src/lib/crypto.js';
import { siteContent } from '../src/site/content.js';
import { harness, SITE } from './support/harness.js';
async function site(role: 'owner' | 'editor' | 'viewer' = 'owner') {
const h = await harness();
const id = '00000000-0000-4000-8000-000000000001';
await h.db.websiteUser.create({ data: { id, name: 'Sam', email: 'sam@hope.test', role } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post' | 'put', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, go, id };
}
describe("the church's shared details, saved through Accounts (decision 10)", () => {
it('sends only what changed, as the signed-in admin', async () => {
const { go, fake, id } = await site();
const r = await go('put', '/church', { church: { serviceTimes: [{ day: 'sunday', time: '09:30', label: 'Morning', campus: null, note: null }] }, ifUpdatedAt: '2026-11-25T08:00:00.000Z' });
assert.equal(r.status, 200);
const sent = fake.requests.at(-1)!;
assert.equal(sent.type, 'church.update');
assert.equal(sent.actor, id);
assert.deepEqual(Object.keys(sent.church!), ['serviceTimes']);
});
it('says so when someone changed the profile in between, and checks the fields first', async () => {
const { go } = await site();
const stale = await go('put', '/church', { church: { name: 'Hope' }, ifUpdatedAt: '2000-01-01T00:00:00.000Z' });
assert.equal(stale.body.error.code, 'PROFILE_CHANGED');
const bad = await go('put', '/church', { church: { contact: { email: null, phone: '012 345', whatsapp: null, address: null } } });
assert.equal(bad.status, 400);
assert.ok(bad.body.error.fields['contact.phone']);
});
it("is an Editor's job, not a Viewer's", async () => {
const { go } = await site('viewer');
assert.equal((await go('put', '/church', { church: { name: 'X' } })).status, 403);
});
});
describe('settings, the menu and the audit log', () => {
it('takes a verification code, or the whole meta tag, and the site shows it', async () => {
const { go, ctx } = await site();
const r = await go('put', '/settings', { googleVerification: '<meta name="google-site-verification" content="abc123XYZ_-" />', bingVerification: 'B1NGcode99', comingSoonText: 'Opening at Easter.' });
assert.equal(r.status, 200);
assert.equal(r.body.googleVerification, 'abc123XYZ_-');
const c = await siteContent(ctx);
assert.deepEqual(c.verification, { google: 'abc123XYZ_-', bing: 'B1NGcode99' });
assert.equal(c.mode === 'coming-soon' && c.comingSoonText, 'Opening at Easter.');
assert.equal((await go('put', '/settings', { googleVerification: '<script>' })).status, 400);
});
it('orders the menu, and the audit log says who did what', async () => {
const { go, db } = await site();
const a = await db.page.create({ data: { kind: 'about', slug: 'about', title: 'About', position: 1 } });
const b = await db.page.create({ data: { kind: 'give', slug: 'give', title: 'Give', position: 2 } });
assert.equal((await go('put', '/pages-order', { ids: [b.id, a.id] })).status, 200);
assert.deepEqual((await go('get', '/pages')).body.map((p: { slug: string }) => p.slug), ['give', 'about']);
await go('put', '/settings', { comingSoonText: 'Soon.' });
const log = (await go('get', '/audit')).body;
assert.deepEqual([log[0].who, log[0].action], ['Sam', 'Changed the settings']);
const overview = (await go('get', '/overview')).body;
assert.equal(overview.recent[0].action, 'Changed the settings');
});
});
+1 -1
View File
@@ -35,7 +35,7 @@ describe('signing in to the admin through Accounts', () => {
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`);
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`);
});
it('makes the Hub\'s admin email (verified) the first Owner and lands on the page they started from', async () => {
+55
View File
@@ -10,6 +10,7 @@ import { siteContent, spotifyEmbed, youtubeId } from '../src/site/content.js';
import { buildPalette, contrast, hexToRgb } from '../src/site/palette.js';
import { parseSectionData } from '../src/site/sections.js';
import { buildSnapshot, cleanDesign, publish } from '../src/site/snapshot.js';
import { thumbnail } from '../src/site/thumbnails.js';
import { defaultDesign } from '../src/site/variants.js';
import { harness } from './support/harness.js';
@@ -137,6 +138,60 @@ describe('the public site\'s content', () => {
});
});
describe("the messages' thumbnails, served from the site (§7)", () => {
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
const youtube = (body: Buffer | string, type = 'image/jpeg', status = 200) => {
const asked: string[] = [];
const fetcher = async (url: string) => { asked.push(url); return new Response(typeof body === 'string' ? body : new Uint8Array(body), { status, headers: { 'content-type': type } }); };
return { asked, fetcher };
};
it("gives visitors the site's own address, never YouTube's", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const content = await siteContent(h.ctx);
assert.ok(content.mode === 'published' && content.messages.length > 0);
for (const m of content.messages) assert.equal(m.thumbnail, '/api/thumbnails/aqz-KE-bpKQ.jpg');
});
it("fetches a message's thumbnail once and keeps it; nothing for a video that isn't the site's", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
const yt = youtube(jpeg);
assert.deepEqual(await thumbnail(h.ctx, 'aqz-KE-bpKQ', yt.fetcher), jpeg);
assert.deepEqual(await thumbnail(h.ctx, 'aqz-KE-bpKQ', yt.fetcher), jpeg);
assert.deepEqual(yt.asked, ['https://i.ytimg.com/vi/aqz-KE-bpKQ/hqdefault.jpg']);
assert.ok(fs.existsSync(path.join(dir, '.thumbnails', 'aqz-KE-bpKQ.jpg')));
// Kept out of /api/uploads (a dot folder).
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/.thumbnails/aqz-KE-bpKQ.jpg')).status));
// Not one of the site's messages, or not an id: YouTube isn't asked.
assert.equal(await thumbnail(h.ctx, 'someoneElse1', yt.fetcher), null);
assert.equal(await thumbnail(h.ctx, '../../etc/x', yt.fetcher), null);
assert.equal(yt.asked.length, 1);
});
it("keeps nothing that isn't a JPEG, and says 404 when YouTube has none", async () => {
const dir = tmp();
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube('<html>', 'text/html').fetcher), null);
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube(Buffer.from('GIF89a'), 'image/jpeg').fetcher), null);
assert.equal(await thumbnail(h.ctx, 'aqz-KE-bpKQ', youtube('', 'image/jpeg', 404).fetcher), null);
assert.ok(!fs.existsSync(path.join(dir, '.thumbnails', 'aqz-KE-bpKQ.jpg')));
h.ctx.fetch = youtube('', 'image/jpeg', 404).fetcher;
const missing = await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.jpg');
assert.equal(missing.status, 404);
assert.equal(missing.headers['cache-control'], 'no-store');
h.ctx.fetch = youtube(jpeg).fetcher;
const ok = await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.jpg');
assert.equal(ok.status, 200);
assert.equal(ok.headers['content-type'], 'image/jpeg');
assert.equal((await request(h.app).get('/api/thumbnails/aqz-KE-bpKQ.png')).status, 404);
});
});
describe('message links', () => {
it('finds YouTube ids and Spotify embeds', () => {
assert.equal(youtubeId('https://www.youtube.com/watch?v=aqz-KE-bpKQ'), 'aqz-KE-bpKQ');
@@ -0,0 +1,74 @@
import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { hub } from '@crosscode/contracts';
import { hashToken } from '../src/lib/crypto.js';
import { stats } from '../src/hub/client.js';
import { harness, SITE } from './support/harness.js';
const SECRET = 'install-secret-0123456789abcdef0123456789';
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
/** The Hub: checks the install's signature as installApi.js does, and records what it's asked. */
async function fakeHub() {
const asked: { installId: string; body: unknown }[] = [];
const app = express();
app.post('/api/installs/storage-request', express.text({ type: () => true }), (req, res) => {
const ts = String(req.get('X-Hub-Timestamp'));
const expected = crypto.createHmac('sha256', SECRET).update(`${ts}.${req.body}`).digest('hex');
if (req.get('X-Hub-Signature') !== expected) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
const body = JSON.parse(req.body);
if (!hub.storageRequestSchema.safeParse(body).success) return res.status(400).json({ code: 'INVALID_REQUEST', message: 'no' });
asked.push({ installId: String(req.get('X-Hub-Install')), body });
return res.status(201).json({ requestedAt: new Date().toISOString(), steps: body.steps, alreadyRequested: asked.length > 1 });
});
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
closers.push(() => new Promise((r) => server.close(r)));
return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, asked };
}
async function site(role: 'owner' | 'editor') {
const fake = await fakeHub();
const h = await harness({ env: { HUB_URL: fake.url } });
await h.ctx.settings.set('hub_install_secret', SECRET);
const id = '00000000-0000-4000-8000-000000000001';
await h.db.websiteUser.create({ data: { id, name: 'Pastor Sam', email: 'sam@hope.test', role } });
await h.db.session.create({ data: { tokenHash: hashToken('t'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
const go = (m: 'get' | 'post', p: string, b?: object) => {
const r = request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=t').set('Origin', SITE);
return b ? r.send(b) : r;
};
return { ...h, fake, go };
}
describe('Get more storage (decision 12)', () => {
it('asks the Hub, signed, with who asked and what is used; shows the request open until the limit goes up', async () => {
const { go, fake, db } = await site('owner');
await db.mediaAsset.create({ data: { filename: 'a.jpg', mime: 'image/jpeg', bytes: 4_500_000_000 } });
const r = await go('post', '/storage-request', { steps: 2 });
assert.equal(r.status, 200);
assert.equal(fake.asked.length, 1);
assert.deepEqual(fake.asked[0]!.body, { protocolVersion: 2, steps: 2, usedBytes: 4_500_000_000, limitBytes: 5 * 1024 ** 3, requestedBy: 'Pastor Sam' });
const media = (await go('get', '/media')).body;
assert.equal(media.request.steps, 2);
assert.equal((await go('post', '/storage-request', { steps: 11 })).status, 400);
});
it('is an Owner\'s or Admin\'s to ask (it costs the church)', async () => {
const { go } = await site('editor');
assert.equal((await go('post', '/storage-request', { steps: 1 })).status, 403);
});
it('reports the licence\'s limit in the heartbeat, so the Hub can email at 80% and 100%', async () => {
const { ctx } = await site('owner');
const s = await stats(ctx);
assert.equal(s.storage.includedBytes, 5 * 1024 ** 3);
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
});
});
+15 -1
View File
@@ -20,6 +20,8 @@ export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
export type FakeAccounts = {
next: Partial<IdentityClaims> & { sub: string };
started: { returnTo: string; requireTwoFactor: boolean }[];
/** Requests to Accounts (people.ensure, …). */
requests: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown> }[];
};
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
@@ -63,6 +65,18 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
throw new SignInError('bad', 'BAD_TOKEN');
}
},
/** people.ensure: the same sub for the same email; "new@…" is a new account. */
request: async (input: { type: string; email?: string; actor?: string | null; church?: Record<string, unknown>; ifUpdatedAt?: string }) => {
fake.requests.push(input);
if (input.type === 'church.update') {
// An old ifUpdatedAt: someone saved in between.
if (input.ifUpdatedAt === '2000-01-01T00:00:00.000Z') throw Object.assign(new Error('changed'), { code: 'PROFILE_CHANGED', status: 409 });
return { schema: 'crosscode.identity-request/1', church: { name: 'Hope', ...input.church } };
}
if (input.type !== 'people.ensure') throw new Error(`not faked: ${input.type}`);
const hex = Buffer.from(input.email ?? '').toString('hex').padEnd(12, '0').slice(0, 12);
return { schema: 'crosscode.identity-request/1', sub: `22222222-2222-4222-8222-${hex}`, created: input.email?.startsWith('new@') ?? false, emailSent: true };
},
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'));
@@ -73,7 +87,7 @@ function fakeAuthClient(fake: FakeAccounts): 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 fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [], requests: [] };
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);
@@ -20,10 +20,10 @@ const DEFAULTS: Record<string, () => Row> = {
siteVersion: () => ({ note: null }),
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
productLink: () => ({ connectedById: null, lastSyncError: null }),
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
};
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
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)]. */
@@ -155,6 +155,7 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
};
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);
if (from === 'productLink') for (const [k, r] of tables.get('importedEvent') ?? []) if (r.linkId === id) tables.get('importedEvent')!.delete(k);
};
const withIncludes = (row: Row, include?: Row) => {
for (const [rel, on] of Object.entries(include ?? {})) {
+2
View File
@@ -2,3 +2,5 @@ test-results/
playwright-report/
.uploads/
screens/
lighthouse/
variants.spec.ts-snapshots/
+23 -4
View File
@@ -100,6 +100,8 @@ test("restore an older version, then publish it", async ({ page, context }) => {
await page.getByRole("button", { name: "Restore" }).click();
await expect(page.getByText("Version 1 is back in your drafts")).toBeVisible();
await page.getByRole("button", { name: "Publish all changes" }).click();
// Wait for it, as above: on real Postgres the publish takes long enough to race the page load.
await expect(page.getByText("Published: visitors see it now.")).toBeVisible();
await page.goto("/about");
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
});
@@ -107,13 +109,13 @@ test("restore an older version, then publish it", async ({ page, context }) => {
test("switch template in the preview, and back, without losing anything", async ({ page, context }) => {
await signIn(context);
await page.goto("/admin/template");
await page.getByRole("button", { name: /^Bold/ }).click();
await page.getByRole("button", { name: "Use Bold" }).click();
await expect(page.getByText("Switched to Bold.")).toBeVisible();
await page.goto("/preview/start");
await expect(page.locator("html")).toHaveAttribute("data-template", "bold");
await expect(page.getByRole("heading", { level: 1, name: "A home for everyone on the hill" })).toBeVisible();
await page.goto("/admin/template");
await page.getByRole("button", { name: /^Heritage/ }).click();
await page.getByRole("button", { name: "Use Heritage" }).click();
await expect(page.getByText("Switched to Heritage.")).toBeVisible();
await page.goto("/admin/publish");
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
@@ -132,9 +134,26 @@ test("a Viewer sees the admin but can't publish", async ({ page, context }) => {
await expect(page.getByRole("button", { name: /Publish/ })).toHaveCount(0);
});
test("the admin's screens are accessible", async ({ page, context }) => {
test("an event added and published shows on the site at once (its own Publish)", async ({ page, context }) => {
await signIn(context);
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/media", "/admin/publish"]) {
await page.goto("/admin/events");
await page.getByRole("button", { name: "Add an event" }).click();
await page.getByLabel("Title").fill("Prayer breakfast");
await page.getByLabel("Date", { exact: true }).fill(new Date(Date.now() + 3 * 864e5).toISOString().slice(0, 10));
await page.getByLabel("Where", { exact: true }).fill("The hall");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Not published").first()).toBeVisible();
await page.getByRole("listitem").filter({ hasText: "Prayer breakfast" }).getByRole("button", { name: "Publish" }).click();
await expect(page.getByText("On the site now.")).toBeVisible();
await page.goto("/events");
await expect(page.getByRole("link", { name: "Prayer breakfast" })).toBeVisible();
});
test("the admin's screens are accessible", async ({ page, context }) => {
// Thirteen screens, each checked by axe.
test.setTimeout(240_000);
await signIn(context, "owner");
for (const path of ["/admin", "/admin/template", "/admin/pages", "/admin/ministries", "/admin/leaders", "/admin/messages", "/admin/events", "/admin/linked", "/admin/media", "/admin/publish", "/admin/settings", "/admin/people", "/admin/audit"]) {
await page.goto(path);
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
+94
View File
@@ -0,0 +1,94 @@
/**
* Lighthouse, mobile (WEBSITE-1.0-PLAN §13, ROADMAP §11 "Checks"): the demo church's home page, an
* event and the messages page in each template, with the template's defaults. SEO 100,
* accessibility 95+, performance 90+. Lighthouse's default run is a phone on a throttled
* connection (simulated), against the production build the other specs use; each page is measured
* three times (LIGHTHOUSE_RUNS), with the CPU slowdown calibrated to this machine
* (calibratedSlowdown), and the median run counts. Its reports go to
* e2e/lighthouse/ (not kept in git) for a look when a score drops.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { chromium, expect, test } from "@playwright/test";
import * as chromeLauncher from "chrome-launcher";
import lighthouse from "lighthouse";
const BACKEND = "http://127.0.0.1:5310";
const SITE = "http://localhost:3310";
const TEMPLATES = ["heritage", "bold", "community", "clean"] as const;
const MIN = { seo: 1, accessibility: 0.95, performance: 0.9 } as const;
const RUNS = Number(process.env.LIGHTHOUSE_RUNS ?? 3);
/**
* Lighthouse's 4× CPU slowdown stands a fast desktop (its benchmark about 1500) in for a mid-range
* phone. On a slower or busy machine the same 4× makes a far slower phone than the target, and the
* score measures the machine: here the benchmark moved from 1450 to 460 between runs a minute
* apart. So a quick probe reads the benchmark first and the slowdown is scaled to it (at least ×1),
* as Lighthouse's throttling notes advise; the thresholds stay the same.
*/
const slowdownFor = (index: number) => Math.round(Math.min(4, Math.max(1, (4 * index) / 1500)) * 10) / 10;
async function calibratedSlowdown(url: string): Promise<number> {
const probe = await lighthouse(`${SITE}${url}`, { port: chrome.port, logLevel: "error", onlyAudits: ["viewport"] });
return slowdownFor(probe?.lhr.environment.benchmarkIndex ?? 1500);
}
/**
* One measured run, calibrated. The machine can slow down between the probe and the run; a run
* whose own benchmark called for a much smaller slowdown than it used is taken again (twice at most).
*/
async function measure(url: string) {
let r;
for (let attempt = 0; attempt < 3; attempt++) {
const slowdown = await calibratedSlowdown(url);
r = await lighthouse(`${SITE}${url}`, { port: chrome.port, output: "html", logLevel: "error", onlyCategories: Object.keys(MIN), throttling: { cpuSlowdownMultiplier: slowdown } as never });
if (!r || slowdown <= slowdownFor(r.lhr.environment.benchmarkIndex) * 1.3) break;
}
return r;
}
const reports = path.join(path.dirname(fileURLToPath(import.meta.url)), "lighthouse");
test.describe.configure({ timeout: 600_000 });
let chrome: chromeLauncher.LaunchedChrome;
test.beforeAll(async () => {
fs.mkdirSync(reports, { recursive: true });
chrome = await chromeLauncher.launch({ chromePath: chromium.executablePath(), chromeFlags: ["--headless=new", "--no-first-run"] });
});
test.afterAll(async () => { await chrome?.kill(); });
for (const template of TEMPLATES) {
test(`${template}: home, an event and the messages, on a phone`, async ({ request, page }) => {
expect((await request.post(`${BACKEND}/test/demo?template=${template}`)).ok()).toBeTruthy();
await page.goto("/events");
const event = await page.locator('main a[href^="/events/"]').first().getAttribute("href");
expect(event).toBeTruthy();
const failed: string[] = [];
for (const [name, url] of [["home", "/"], ["event", event!], ["messages", "/messages"]] as const) {
// Once to warm the server, then measured RUNS times; the median run (by performance) counts,
// as Lighthouse advises: one run's total blocking time moves by 200ms+ on a busy machine.
await request.get(url);
const runs = [];
for (let n = 0; n < RUNS; n++) {
const r = await measure(url);
expect(r, `${template} ${name}`).toBeTruthy();
runs.push(r!);
}
runs.sort((a, b) => (a.lhr.categories.performance?.score ?? 0) - (b.lhr.categories.performance?.score ?? 0));
const result = runs[Math.floor(RUNS / 2)];
fs.writeFileSync(path.join(reports, `${template}-${name}.html`), String(result!.report));
const scores = Object.fromEntries(Object.keys(MIN).map((c) => [c, result!.lhr.categories[c]?.score ?? 0]));
const env = result!.lhr.environment;
console.log(`[lighthouse] ${template} ${name}: ${Object.entries(scores).map(([c, s]) => `${c} ${Math.round(s * 100)}`).join(", ")} (benchmark ${Math.round(env.benchmarkIndex)}, CPU ×${result!.lhr.configSettings.throttling.cpuSlowdownMultiplier})`);
for (const [c, min] of Object.entries(MIN)) {
if (scores[c]! < min) {
const audits = Object.values(result!.lhr.audits).filter((a) => a.score !== null && a.score < 0.9 && (result!.lhr.categories[c]?.auditRefs ?? []).some((r) => r.id === a.id && r.weight > 0));
failed.push(`${template} ${name} ${c} ${Math.round(scores[c]! * 100)} < ${min * 100}: ${audits.map((a) => `${a.id}${a.displayValue ? ` (${a.displayValue})` : ""}`).join(", ")}`);
}
}
}
expect(failed).toEqual([]);
});
}
+43 -5
View File
@@ -1,30 +1,68 @@
/**
* The e2e backend (playwright.config.ts): the Website's backend on port 5310 with the in-memory
* database from the backend tests (no Postgres needed) and the demo church published. The pages
* run with `next dev` on 3310 and send /api here.
* database from the backend tests (no Postgres needed), or a real Postgres with E2E_DATABASE_URL
* (freshPostgres, below), and the demo church published. The pages run as a production build on
* 3310 and send /api here.
*
* Test helpers: POST /test/demo?template=<id> loads the demo church on that template;
* POST /test/design { variants?, style?, home? } changes the design and publishes again.
*/
import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import pg from 'pg';
import sharp from 'sharp';
import { PrismaPg } from '@prisma/adapter-pg';
import { websiteTemplateSchema } from '@crosscode/contracts';
import { PrismaClient } from '../backend/src/generated/prisma/client.js';
import { createApp } from '../backend/src/app.js';
import { createCtx } from '../backend/src/context.js';
import { loadDemo } from '../backend/src/demo/demoChurch.js';
import { illustration, loadDemo } from '../backend/src/demo/demoChurch.js';
import { loadConfig } from '../backend/src/lib/config.js';
import { hashToken } from '../backend/src/lib/crypto.js';
import { publish } from '../backend/src/site/snapshot.js';
import { memoryDb } from '../backend/tests/support/memoryDb.js';
const { Client } = pg;
const here = path.dirname(fileURLToPath(import.meta.url));
const uploads = path.join(here, '.uploads');
fs.mkdirSync(uploads, { recursive: true });
const db = memoryDb();
const ctx = createCtx(loadConfig({ WEBSITE_URL: 'http://localhost:3310', NODE_ENV: 'test', JOBS_ENABLED: 'false', HUB_URL: 'http://127.0.0.1:1', UPLOAD_DIR: uploads, TRUST_PROXY: 'true' }), db as never);
const db = process.env.E2E_DATABASE_URL ? await freshPostgres(process.env.E2E_DATABASE_URL) : memoryDb();
/**
* The real-Postgres run (WEBSITE-1.0-PLAN §13): `E2E_DATABASE_URL=postgresql://…/ccw_website_e2e npx
* playwright test`. The database is dropped and made again, the migrations applied with `prisma
* migrate deploy` (as `crosscode deploy` does), and the same suite runs on it. The name must end in
* `_e2e`, so a real site's database is never dropped.
*/
async function freshPostgres(url: string) {
const target = new URL(url);
const name = target.pathname.slice(1);
if (!/^[a-z0-9_]+_e2e$/.test(name)) throw new Error(`E2E_DATABASE_URL must name a database ending in _e2e (got "${name}").`);
const admin = new URL(url);
admin.pathname = '/postgres';
const pg = new Client({ connectionString: admin.toString() });
await pg.connect();
await pg.query(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);
await pg.query(`CREATE DATABASE ${name}`);
await pg.end();
execSync('npx prisma migrate deploy', { cwd: path.join(here, '../backend'), env: { ...process.env, DATABASE_URL: url }, stdio: 'inherit' });
console.log(`[e2e] On Postgres: ${name}, migrations applied.`);
return new PrismaClient({ adapter: new PrismaPg({ connectionString: url }) });
}
// A frozen clock (a Monday morning), so the demo's dates, and so the screenshots, are the same every
// run (variants.spec.ts). E2E_NOW changes it.
const frozen = new Date(process.env.E2E_NOW ?? '2026-11-23T06:00:00Z');
// YouTube's thumbnails (site/thumbnails.ts) without the network: one of the demo's illustrations,
// as a JPEG the size of YouTube's, for every video.
const thumb = await sharp(Buffer.from(illustration(4, 480, 360))).jpeg().toBuffer();
const fakeYoutube = async (url: string) => url.startsWith('https://i.ytimg.com/')
? new Response(new Uint8Array(thumb), { headers: { 'content-type': 'image/jpeg' } })
: new Response('not here', { status: 404 });
const ctx = createCtx(loadConfig({ WEBSITE_URL: 'http://localhost:3310', NODE_ENV: 'test', JOBS_ENABLED: 'false', HUB_URL: 'http://127.0.0.1:1', UPLOAD_DIR: uploads, TRUST_PROXY: 'true' }), db as never, { now: () => new Date(frozen), fetch: fakeYoutube });
await loadDemo(ctx, websiteTemplateSchema.parse(process.env.DEMO_TEMPLATE ?? 'heritage'), { uploadDir: uploads });
const app = express();
+50
View File
@@ -64,6 +64,19 @@ test("the home page has the church's JSON-LD; unknown pages are a real 404", asy
expect((await page.goto("/no-such-page"))?.status()).toBe(404);
});
test("the messages ask nothing of YouTube until play is clicked; their thumbnails come from the site", async ({ page }) => {
await useTemplate(page, "heritage");
const outside: string[] = [];
page.on("request", (r) => { if (/youtube|ytimg|spotify/.test(new URL(r.url()).hostname)) outside.push(r.url()); });
await page.goto("/messages");
const thumb = page.locator("main img").first();
await expect(thumb).toHaveAttribute("src", /^\/api\/thumbnails\/[\w-]+\.jpg$/);
await expect.poll(() => thumb.evaluate((i: HTMLImageElement) => i.naturalWidth)).toBeGreaterThan(0);
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForLoadState("networkidle");
expect(outside).toEqual([]);
});
test("robots.txt keeps the admin out; the sitemap lists the pages", async ({ page }) => {
const robots = await (await page.request.get("/robots.txt")).text();
expect(robots).toContain("Disallow: /admin");
@@ -71,3 +84,40 @@ test("robots.txt keeps the admin out; the sitemap lists the pages", async ({ pag
expect(sitemap).toContain("/visit</loc>");
expect(sitemap).not.toContain("/admin");
});
test("structured data on event and other pages, a made share image, the verification codes, a moved page", async ({ page }) => {
const backend = "http://127.0.0.1:5310";
await page.request.post(`${backend}/test/demo?template=heritage`);
await page.goto("/events");
const ld = (await page.locator('script[type="application/ld+json"]').allTextContents()).map((t) => JSON.parse(t));
expect(ld.some((x) => x["@type"] === "BreadcrumbList")).toBeTruthy();
await page.getByRole("link", { name: "Family picnic" }).first().click();
await expect(page.getByRole("heading", { level: 1, name: "Family picnic" })).toBeVisible();
const eventLd = (await page.locator('script[type="application/ld+json"]').allTextContents()).map((t) => JSON.parse(t));
const ev = eventLd.find((x) => x["@type"] === "Event");
expect(ev.name).toBe("Family picnic");
expect(ev.location["@type"]).toBe("Place");
// Pages without their own photo share a made image.
await page.goto("/visit");
const og = await page.locator('meta[property="og:image"]').getAttribute("content");
expect(og).toContain("/share-image?t=");
const img = await page.request.get(new URL(og!).pathname + new URL(og!).search);
expect(img.status()).toBe(200);
expect(img.headers()["content-type"]).toBe("image/png");
// An admin sets the codes and moves a page; the old address goes on to the new one.
const { cookie } = await (await page.request.post(`${backend}/test/session?role=editor`)).json();
const headers = { Cookie: `ccw_session=${cookie.value}`, Origin: "http://localhost:3310", "Content-Type": "application/json" };
await page.request.put("/api/v1/admin/settings", { headers, data: { googleVerification: "googleCode123", bingVerification: "bingCode456" } });
const pages = await (await page.request.get("/api/v1/admin/pages", { headers })).json();
const visit = pages.find((p: { kind: string }) => p.kind === "visit");
expect((await page.request.put(`/api/v1/admin/pages/${visit.id}`, { headers, data: { slug: "first-visit" } })).ok()).toBeTruthy();
expect((await page.request.post("/api/v1/admin/publish", { headers, data: {} })).ok()).toBeTruthy();
const moved = await page.request.get("/visit", { maxRedirects: 0 });
expect([301, 308]).toContain(moved.status());
expect(moved.headers().location).toContain("/first-visit");
await page.goto("/");
expect(await page.locator('meta[name="google-site-verification"]').getAttribute("content")).toBe("googleCode123");
expect(await page.locator('meta[name="msvalidate.01"]').getAttribute("content")).toBe("bingCode456");
});
+98
View File
@@ -0,0 +1,98 @@
/**
* Every section variant in every template (WEBSITE-1.0-PLAN §3, "Checks per variant", and §13): the
* demo church's homepage with all eight sections showing, one variant changed at a time. For each,
* axe finds no violations (WCAG 2.2 AA) and the section looks as it did last time at phone, tablet
* and desktop width: 26 variants × 4 templates × 3 widths = 312 screenshots, compared with
* `toHaveScreenshot` against the baselines in e2e/variants.spec.ts-snapshots/.
*
* The baselines aren't in git (about 20 MB, and each operating system draws text a little
* differently): they're kept on the machine that runs the release checks. Take them at a release
* (`npx playwright test variants --update-snapshots`, then look through them), and the next
* release's run shows every section that changed. The e2e server freezes the clock (E2E_NOW), so
* the demo's dates never change between runs. What comes from outside is masked: the video, the
* map (OpenStreetMap) and the messages' thumbnails.
*/
import AxeBuilder from "@axe-core/playwright";
import { expect, test, type Page } from "@playwright/test";
import { SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_VARIANTS } from "../backend/src/site/variants.js";
const BACKEND = "http://127.0.0.1:5310";
const TEMPLATES = Object.keys(TEMPLATE_VARIANTS) as (keyof typeof TEMPLATE_VARIANTS)[];
const WIDTHS = [["phone", { width: 390, height: 844 }], ["tablet", { width: 820, height: 1180 }], ["desktop", { width: 1366, height: 900 }]] as const;
// Every section showing, in a fixed order, so the nth <section> in <main> is the nth type here.
const HOME = SECTION_TYPES.map((section) => ({ section, hidden: false }));
async function design(page: Page, variants: Record<string, string>) {
const res = await page.request.post(`${BACKEND}/test/design`, { data: { variants, home: HOME } });
expect(res.ok()).toBeTruthy();
}
/**
* Lazy images load only once scrolled to: go through the page, then wait for every image. The
* site's own images must really have loaded (a broken one is "complete" too).
*/
async function loadImages(page: Page) {
await page.evaluate(async () => {
for (let y = 0; y < document.body.scrollHeight; y += 500) { window.scrollTo(0, y); await new Promise((r) => setTimeout(r, 40)); }
window.scrollTo(0, 0);
});
await page.waitForFunction(() => Array.from(document.images).every((i) => i.complete), null, { timeout: 30_000 });
const broken = await page.evaluate(() => Array.from(document.images)
.filter((i) => new URL(i.currentSrc || i.src, location.href).origin === location.origin && i.naturalWidth === 0)
.map((i) => i.currentSrc || i.src));
expect(broken, "images that didn't load").toEqual([]);
}
/**
* A section's screenshot is as big as its box, rounded where it starts and ends on the page. With
* fractional heights above it (text, aspect ratios), the same section came out a pixel taller or
* shorter from run to run, which fails `toHaveScreenshot` however small the difference. So the
* header and every section get their own height rounded up first: each section then starts on a
* whole pixel and is the same size every run.
*/
async function wholePixels(page: Page) {
await page.evaluate(() => {
// The header and the sections, not what holds them (main grows to fit).
const blocks = Array.from(document.querySelectorAll<HTMLElement>("header:not(main header), main > section"));
for (const b of blocks) b.style.height = "";
const heights = blocks.map((b) => b.getBoundingClientRect().height);
blocks.forEach((b, n) => { if (getComputedStyle(b).position !== "fixed") b.style.height = `${Math.ceil(heights[n]!)}px`; });
});
}
for (const template of TEMPLATES) {
test.describe(`${template} variants`, () => {
test.beforeAll(async ({ request }) => {
expect((await request.post(`${BACKEND}/test/demo?template=${template}`)).ok()).toBeTruthy();
});
for (const [i, type] of SECTION_TYPES.entries()) {
for (const variant of SECTION_VARIANTS[type]) {
test(`${type}: ${variant}`, async ({ page }) => {
await design(page, { [type]: variant });
await page.setViewportSize(WIDTHS[2][1]);
expect((await page.goto("/"))?.status()).toBe(200);
await expect(page.locator("html")).toHaveAttribute("data-template", template);
const sections = page.locator("main > section");
await expect(sections).toHaveCount(SECTION_TYPES.length);
await loadImages(page);
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
expect(axe.violations.map((v) => `${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
const section = sections.nth(i);
for (const [name, size] of WIDTHS) {
await page.setViewportSize(size);
await loadImages(page);
await wholePixels(page);
await expect(section).toHaveScreenshot(`${template}-${type}-${variant}-${name}.png`, {
mask: [page.locator("main video"), page.locator("main [data-map]"), page.locator('main img[src*="/api/thumbnails/"]')],
animations: "disabled",
maxDiffPixelRatio: 0.01,
});
}
});
}
}
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/website-frontend",
"version": "0.1.0",
"version": "1.0.2",
"private": true,
"description": "Church Website: the church's public site in its template, and the admin",
"scripts": {
@@ -34,7 +34,9 @@ export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }:
const { busy, message, fields: errors, run } = useAction();
if (!data) return <Loading error={error} />;
const save = (id: string | null, v: Record<string, unknown>) => run(async () => {
const body = Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null]));
const row = id ? data.find((r) => r.id === id) : null;
// When the form was loaded: someone else's save in between isn't overwritten (§4).
const body = { ...Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null])), ...(row?.updatedAt ? { ifUpdatedAt: row.updatedAt } : {}) };
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
setEditing(null);
await reload();
+8 -1
View File
@@ -9,11 +9,18 @@ import { cx, useAdmin } from "./ui";
const NAV = [
{ href: "/admin", label: "Dashboard" },
{ href: "/admin/template", label: "Template and style" },
{ href: "/admin/church", label: "Church details" },
{ href: "/admin/pages", label: "Pages" },
{ href: "/admin/ministries", label: "Ministries" },
{ href: "/admin/leaders", label: "Leadership" },
{ href: "/admin/messages", label: "Messages" },
{ href: "/admin/events", label: "Events" },
{ href: "/admin/linked", label: "Linked products" },
{ href: "/admin/media", label: "Media library" },
{ href: "/admin/publish", label: "Publish and history" },
{ href: "/admin/settings", label: "Settings" },
{ href: "/admin/people", label: "People", managers: true },
{ href: "/admin/audit", label: "Audit log", managers: true },
];
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
@@ -36,7 +43,7 @@ export function AdminShell({ user, children }: { user: { name: string; role: str
<div className="mx-auto grid max-w-6xl gap-6 px-4 py-6 md:grid-cols-[13rem_1fr]">
<nav aria-label="Admin">
<ul className="flex gap-1 overflow-x-auto md:flex-col">
{NAV.map((n) => {
{NAV.filter((n) => !("managers" in n) || ["owner", "admin"].includes(user.role)).map((n) => {
const current = n.href === "/admin" ? path === "/admin" : path.startsWith(n.href);
return (
<li key={n.href}>
+1 -1
View File
@@ -82,7 +82,7 @@ export function ImagePicker({ value, onChange, label }: { value: string | null;
</div>
<div className="mt-6 border-t border-gray-200 pt-4">
<h3 className="mb-2 font-semibold">Upload a new one</h3>
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. To get more (5 GB at a time), contact Cross Code.</Notice>}
{data?.storage.full && <Notice tone="warning">Your storage is full, so uploads have stopped. An Owner or Admin can get more under Media library.</Notice>}
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
</div>
</div>
+14 -5
View File
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { notFound, permanentRedirect, redirect } from "next/navigation";
import { loadContent } from "@/site/load";
import { churchLd, pageMetadata } from "@/site/meta";
import { breadcrumbLd, churchLd, messagesLd, pageMetadata } from "@/site/meta";
import { PageView } from "@/site/PageView";
import { Shell } from "@/site/Shell";
@@ -23,11 +23,20 @@ export default async function SitePage({ params }: Props) {
const { c, page } = await find(slug);
// Before the first publish every address shows Coming soon, on the home page.
if (c.mode !== "published") redirect("/");
if (!page) notFound();
const ld = page.kind === "contact" ? churchLd(c, page.path) : null;
if (!page) {
// A page's earlier address: on to where it is now, permanently (§6).
const moved = c.snapshot.redirects?.[slug];
if (moved) permanentRedirect(moved);
notFound();
}
const lds = [
breadcrumbLd(c, [{ name: page.title, path: page.path }]),
page.kind === "contact" ? churchLd(c, page.path) : null,
page.kind === "messages" ? messagesLd(c, c.messages) : null,
].filter((x): x is string => !!x);
return (
<Shell site={c} path={page.path}>
{ld && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />}
{lds.map((ld, i) => <script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />)}
<PageView page={page} site={c} />
</Shell>
);
@@ -0,0 +1,43 @@
"use client";
/** The audit log (§4, §10): who changed what, and when. Owners and Admins see it. */
import { useState } from "react";
import { api } from "@/admin/api";
import { Btn, Loading, Panel, Title, useAdmin, when } from "@/admin/ui";
type Entry = { at: string; who: string; action: string; detail: string | null };
export default function Audit() {
const first = useAdmin<Entry[]>("/audit");
const [more, setMore] = useState<Entry[]>([]);
const [done, setDone] = useState(false);
if (!first.data) return <Loading error={first.error} />;
const all = [...first.data, ...more];
return (
<>
<Title sub="Who changed what, newest first.">Audit log</Title>
<Panel>
{all.length === 0 && <p className="text-gray-600">Nothing yet.</p>}
<table className="w-full text-left text-sm">
<thead className="text-gray-600"><tr><th className="py-2 pr-4 font-medium">When</th><th className="py-2 pr-4 font-medium">Who</th><th className="py-2 font-medium">What</th></tr></thead>
<tbody className="divide-y divide-gray-200">
{all.map((e, i) => (
<tr key={`${e.at}-${i}`}>
<td className="whitespace-nowrap py-2 pr-4 text-gray-600">{when(e.at)}</td>
<td className="py-2 pr-4">{e.who}</td>
<td className="py-2">{e.action}{e.detail && <span className="text-gray-600">: {e.detail}</span>}</td>
</tr>
))}
</tbody>
</table>
{!done && all.length >= 100 && (
<Btn className="mt-4" onClick={async () => {
const next = await api<Entry[]>(`/audit?before=${encodeURIComponent(all.at(-1)!.at)}`);
if (!next.length) setDone(true);
setMore([...more, ...next]);
}}>Show older</Btn>
)}
</Panel>
</>
);
}
@@ -0,0 +1,127 @@
"use client";
/**
* Church details (§2, decision 10): the facts every one of the church's sites shows (name, colours,
* fonts and corners, logo, service times, contact, social links). They belong to the church's
* Accounts and are saved there; they're not drafts: they change on all its sites at once.
*/
import { useState } from "react";
import type { Church } from "@crosscode/contracts";
import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
const DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
const PAIRINGS: [string, string][] = [["", "Your template's choice"], ["classic", "Classic"], ["scholarly", "Scholarly"], ["editorial", "Editorial"], ["impact", "Impact"], ["contemporary", "Contemporary"], ["friendly", "Friendly"], ["warm", "Warm"], ["modern", "Modern"]];
const NETWORKS = ["facebook", "instagram", "youtube", "tiktok", "x", "spotify", "whatsapp-channel", "other"];
type ServiceTime = Church["serviceTimes"][number];
type Social = Church["social"][number];
type Address = NonNullable<Church["contact"]["address"]>;
export default function ChurchDetails() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<{ church: Church | null; linked: boolean }>("/church");
const { busy, message, fields, run } = useAction();
const [edit, setEdit] = useState<Partial<Church> & { logoMediaId?: string | null } | null>(null);
if (!data || !me.data) return <Loading error={error ?? me.error} />;
if (!data.church) return <><Title>Church details</Title><Notice tone="warning">{data.linked ? "Your church's details can't be read from Accounts right now. Try again in a minute." : "This website isn't linked to your church's Accounts yet. It links by itself within 15 minutes of being installed."}</Notice></>;
const c: Church = { ...data.church, ...edit } as Church;
const editor = canEdit(me.data.user.role);
const set = (patch: Partial<Church>) => setEdit({ ...edit, ...patch });
const times = c.serviceTimes;
const setTime = (i: number, t: Partial<ServiceTime>) => set({ serviceTimes: times.map((x, j) => (j === i ? { ...x, ...t } : x)) });
const address: Address = c.contact.address ?? { line1: "", line2: null, suburb: null, city: "", province: null, postalCode: null, country: "ZA", geo: null };
const setAddress = (a: Partial<Address>) => set({ contact: { ...c.contact, address: { ...address, ...a } } });
const save = () => run(async () => {
// The media id only picks the logo here; Accounts keeps its address.
const changes = { ...(edit ?? {}) };
delete changes.logoMediaId;
await api("/church", { method: "PUT", body: { church: changes, ifUpdatedAt: data.church!.updatedAt } });
setEdit(null);
await reload();
}, "Saved: all your church's sites show it now.");
const err = (k: string) => fields[k];
return (
<>
<Title sub="These show on all your church's sites (this website, Cross Events, the sign-in pages). Changes here go live straight away: they aren't drafts."
actions={editor && edit && <><Btn onClick={() => setEdit(null)}>Undo</Btn><Btn kind="primary" busy={busy} onClick={save}>Save for all your sites</Btn></>}>
Church details
</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<fieldset disabled={!editor} className="space-y-6">
<Panel title="Name and look">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Church name" error={err("name")}><input className={inputClass} value={c.name} maxLength={200} onChange={(e) => set({ name: e.target.value })} /></Field>
<Field label="Short name" hint="For tight spaces." error={err("shortName")}><input className={inputClass} value={c.shortName ?? ""} maxLength={30} onChange={(e) => set({ shortName: e.target.value || null })} /></Field>
<Field label="Main colour" error={err("branding.colours.primary")}><input type="color" className="h-10 w-20" value={c.branding.colours.primary} onChange={(e) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, primary: e.target.value } } })} /></Field>
<Field label="Accent colour"><input type="color" className="h-10 w-20" value={c.branding.colours.accent ?? "#999999"} onChange={(e) => set({ branding: { ...c.branding, colours: { ...c.branding.colours, accent: e.target.value } } })} /></Field>
<Field label="Fonts" hint="Shared by all your sites. Your template suggests some.">
<select className={inputClass} value={c.branding.style?.fontPairing ?? ""} onChange={(e) => set({ branding: { ...c.branding, style: { fontPairing: (e.target.value || null) as never, corners: c.branding.style?.corners ?? null } } })}>
{PAIRINGS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
</select>
</Field>
<Field label="Corners">
<select className={inputClass} value={c.branding.style?.corners ?? ""} onChange={(e) => set({ branding: { ...c.branding, style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: (e.target.value || null) as never } } })}>
<option value="">Your template&apos;s choice</option><option value="sharp">Sharp</option><option value="soft">Soft</option><option value="round">Round</option>
</select>
</Field>
<div className="sm:col-span-2">
{c.branding.logoUrl && <img src={c.branding.logoUrl} alt="Your logo" className="mb-2 h-12 w-auto" />}
<ImagePicker label="Logo (a photo from the media library)" value={edit?.logoMediaId ?? null}
onChange={(id) => run(async () => {
if (!id) return set({ branding: { ...c.branding, logoUrl: null }, logoMediaId: null } as never);
const media = await api<{ items: { id: string; url: string }[] }>("/media");
const url = media.items.find((m) => m.id === id)?.url;
set({ branding: { ...c.branding, logoUrl: url ? `${window.location.origin}${url}` : null }, logoMediaId: id } as never);
})} />
</div>
</div>
</Panel>
<Panel title="Service times">
<ul className="space-y-3">
{times.map((t, i) => (
<li key={i} className="grid gap-2 sm:grid-cols-[8rem_7rem_1fr_1fr_auto]">
<select aria-label="Day" className={inputClass} value={t.day} onChange={(e) => setTime(i, { day: e.target.value as ServiceTime["day"] })}>{DAYS.map((d) => <option key={d} value={d}>{d[0]!.toUpperCase() + d.slice(1)}</option>)}</select>
<input aria-label="Time" type="time" className={inputClass} value={t.time} onChange={(e) => setTime(i, { time: e.target.value })} />
<input aria-label="Name (e.g. Morning service)" placeholder="E.g. Morning service" className={inputClass} value={t.label ?? ""} maxLength={100} onChange={(e) => setTime(i, { label: e.target.value || null })} />
<input aria-label="Note" placeholder="E.g. Kids church during the service" className={inputClass} value={t.note ?? ""} maxLength={300} onChange={(e) => setTime(i, { note: e.target.value || null })} />
<Btn kind="danger" onClick={() => set({ serviceTimes: times.filter((_, j) => j !== i) })}>Remove</Btn>
</li>
))}
</ul>
{err("serviceTimes") && <p className="mt-2 text-xs text-red-700">{err("serviceTimes")}</p>}
<Btn className="mt-3" onClick={() => set({ serviceTimes: [...times, { day: "sunday", time: "09:00", label: null, campus: null, note: null }] })}>Add a service time</Btn>
</Panel>
<Panel title="Contact and address">
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Email" error={err("contact.email")}><input type="email" className={inputClass} value={c.contact.email ?? ""} onChange={(e) => set({ contact: { ...c.contact, email: e.target.value || null } })} /></Field>
<Field label="Phone" hint="With the country code: +27125550123" error={err("contact.phone")}><input className={inputClass} value={c.contact.phone ?? ""} onChange={(e) => set({ contact: { ...c.contact, phone: e.target.value.replace(/\s+/g, "") || null } })} /></Field>
<Field label="WhatsApp" hint="With the country code" error={err("contact.whatsapp")}><input className={inputClass} value={c.contact.whatsapp ?? ""} onChange={(e) => set({ contact: { ...c.contact, whatsapp: e.target.value.replace(/\s+/g, "") || null } })} /></Field>
<div />
<Field label="Street address" error={err("contact.address.line1")}><input className={inputClass} value={address.line1} onChange={(e) => setAddress({ line1: e.target.value })} /></Field>
<Field label="Suburb"><input className={inputClass} value={address.suburb ?? ""} onChange={(e) => setAddress({ suburb: e.target.value || null })} /></Field>
<Field label="City" error={err("contact.address.city")}><input className={inputClass} value={address.city} onChange={(e) => setAddress({ city: e.target.value })} /></Field>
<Field label="Postal code"><input className={inputClass} value={address.postalCode ?? ""} onChange={(e) => setAddress({ postalCode: e.target.value || null })} /></Field>
</div>
</Panel>
<Panel title="Social links">
<ul className="space-y-2">
{c.social.map((s, i) => (
<li key={i} className="grid gap-2 sm:grid-cols-[12rem_1fr_auto]">
<select aria-label="Network" className={inputClass} value={s.network} onChange={(e) => set({ social: c.social.map((x, j) => (j === i ? { ...x, network: e.target.value as Social["network"] } : x)) })}>{NETWORKS.map((n) => <option key={n} value={n}>{n}</option>)}</select>
<input aria-label="Address" className={inputClass} value={s.url} onChange={(e) => set({ social: c.social.map((x, j) => (j === i ? { ...x, url: e.target.value } : x)) })} />
<Btn kind="danger" onClick={() => set({ social: c.social.filter((_, j) => j !== i) })}>Remove</Btn>
</li>
))}
</ul>
{err("social") && <p className="mt-2 text-xs text-red-700">{err("social")}</p>}
<Btn className="mt-3" onClick={() => set({ social: [...c.social, { network: "facebook", url: "https://" }] })}>Add a link</Btn>
</Panel>
</fieldset>
</>
);
}
@@ -0,0 +1,136 @@
"use client";
/**
* Simple events (§8): title, date and time, place, description, a photo and an optional link (a
* sign-up form elsewhere, say). Registrations and payments are Cross Events'. Each publishes on its
* own (decision 9). An event can belong to a ministry: its Ministry leader can add and change it,
* and an Editor publishes it (§10). Events from Cross Events show on the site by themselves.
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Ev = {
id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null;
imageId: string | null; image: string | null; link: string | null; ministryId: string | null; cancelled: boolean; published: boolean; updatedAt: string;
};
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; link: string; ministryId: string | null };
type Me = { user: { role: string; ministryId: string | null } };
/** "2026-12-05" + "18:30" in the browser's time zone (the church's, for its admins) → ISO with offset. */
const iso = (date: string, time: string) => (date ? new Date(`${date}T${time || "00:00"}`).toISOString() : null);
const local = (s: string | null) => {
if (!s) return { d: "", t: "" };
const x = new Date(s);
const p = (n: number) => String(n).padStart(2, "0");
return { d: `${x.getFullYear()}-${p(x.getMonth() + 1)}-${p(x.getDate())}`, t: `${p(x.getHours())}:${p(x.getMinutes())}` };
};
function EventForm({ initial, ministries, fixedMinistry, onSave, onCancel }: { initial: Form; ministries: { id: string; name: string }[]; fixedMinistry: string | null; onSave: (body: object) => Promise<unknown>; onCancel: () => void }) {
const [v, setV] = useState(initial);
const { busy, message, fields, run } = useAction();
const set = (k: keyof Form, x: unknown) => setV({ ...v, [k]: x });
return (
<div className="space-y-3">
<Field label="Title" error={fields.title}><input className={inputClass} value={v.title} maxLength={300} onChange={(e) => set("title", e.target.value)} /></Field>
<div className="grid gap-3 sm:grid-cols-4">
<Field label="Date" error={fields.startsAt}><input type="date" className={inputClass} value={v.date} onChange={(e) => set("date", e.target.value)} /></Field>
{!v.allDay && <Field label="Time"><input type="time" className={inputClass} value={v.time} onChange={(e) => set("time", e.target.value)} /></Field>}
<Field label="Ends (date)" error={fields.endsAt}><input type="date" className={inputClass} value={v.endDate} onChange={(e) => set("endDate", e.target.value)} /></Field>
{!v.allDay && <Field label="Ends (time)"><input type="time" className={inputClass} value={v.endTime} onChange={(e) => set("endTime", e.target.value)} /></Field>}
</div>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={v.allDay} onChange={(e) => set("allDay", e.target.checked)} />All day</label>
<Field label="Where" error={fields.location}><input className={inputClass} value={v.location} maxLength={500} onChange={(e) => set("location", e.target.value)} /></Field>
<Field label="About it" error={fields.description}><textarea className={inputClass} rows={4} value={v.description} maxLength={8000} onChange={(e) => set("description", e.target.value)} /></Field>
<Field label="Link (optional)" hint="A sign-up form or more information elsewhere: https://…" error={fields.link}><input className={inputClass} value={v.link} onChange={(e) => set("link", e.target.value)} /></Field>
{!fixedMinistry && ministries.length > 0 && (
<Field label="Ministry (optional)" hint="Its Ministry leader can then change it too.">
<select className={inputClass} value={v.ministryId ?? ""} onChange={(e) => set("ministryId", e.target.value || null)}>
<option value="">None</option>
{ministries.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
</select>
</Field>
)}
<ImagePicker label="Photo" value={v.imageId} onChange={(id) => set("imageId", id)} />
<div className="flex gap-2">
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave({
title: v.title, startsAt: iso(v.date, v.allDay ? "00:00" : v.time), endsAt: v.endDate ? iso(v.endDate, v.allDay ? "23:59" : v.endTime) : null,
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, link: v.link || null, ministryId: fixedMinistry ?? v.ministryId,
}))}>Save</Btn>
<Btn onClick={onCancel}>Cancel</Btn>
</div>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
);
}
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, link: "", ministryId: null };
export default function Events() {
const me = useAdmin<Me>("/me");
const { data, error, reload } = useAdmin<Ev[]>("/events");
const ministries = useAdmin<{ id: string; name: string }[]>("/ministries");
const [editing, setEditing] = useState<string | null>(null);
const { busy, message, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const leaderOf = me.data.user.role === "ministry_leader" ? me.data.user.ministryId : null;
const mayWrite = (e: Ev | null) => editor || (!!leaderOf && (!e || e.ministryId === leaderOf));
const nameOf = (id: string | null) => ministries.data?.find((m) => m.id === id)?.name;
const toForm = (e: Ev): Form => {
const s = local(e.startsAt);
const f = local(e.endsAt);
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, link: e.link ?? "", ministryId: e.ministryId };
};
const state = (e: Ev, change: object, done: string) => run(async () => { await api(`/events/${e.id}/state`, { body: change }); await reload(); }, done);
const form = (e: Ev | null) => (
<EventForm initial={e ? toForm(e) : { ...empty, ministryId: leaderOf }} ministries={ministries.data ?? []} fixedMinistry={leaderOf} onCancel={() => setEditing(null)}
onSave={async (b) => {
await api(e ? `/events/${e.id}` : "/events", { method: e ? "PUT" : "POST", body: e ? { ...b, ifUpdatedAt: e.updatedAt } : b });
setEditing(null);
await reload();
}} />
);
return (
<>
<Title sub={leaderOf ? `You can add and change ${nameOf(leaderOf) ?? "your ministry"}'s events; an editor publishes them.` : "Simple events made here. Events with registration and payment belong in Cross Events; they show here by themselves once it's linked."}>Events</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
{mayWrite(null) && (
<Panel title="Add an event">
{editing === "new" ? form(null) : <Btn kind="primary" onClick={() => setEditing("new")}>Add an event</Btn>}
</Panel>
)}
<Panel title="Your events">
{data.length === 0 && <p className="text-gray-600">None yet.</p>}
<ul className="divide-y divide-gray-200">
{data.map((e) => (
<li key={e.id} className="py-3">
{editing === e.id ? form(e) : (
<div className="flex flex-wrap items-center gap-4">
<div className="min-w-0 flex-1">
<p className="font-medium">{e.title}</p>
<p className="text-sm text-gray-600">{when(e.startsAt)}{e.location && ` · ${e.location}`}{e.ministryId && nameOf(e.ministryId) && ` · ${nameOf(e.ministryId)}`}</p>
<p className="text-xs">{e.cancelled ? <span className="text-red-700">Cancelled</span> : e.published ? <span className="text-green-800">On the site</span> : <span className="text-gray-500">Not published</span>}</p>
</div>
<div className="flex flex-wrap gap-2">
{mayWrite(e) && <Btn onClick={() => setEditing(e.id)}>Edit</Btn>}
{editor && (
<>
<Btn busy={busy} onClick={() => state(e, { published: !e.published }, e.published ? "Taken off the site." : "On the site now.")}>{e.published ? "Unpublish" : "Publish"}</Btn>
<Btn busy={busy} onClick={() => state(e, { cancelled: !e.cancelled }, e.cancelled ? "Back on." : "Cancelled: it's off the site.")}>{e.cancelled ? "Not cancelled" : "Cancel it"}</Btn>
<Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/events/${e.id}`, { method: "DELETE" }); await reload(); }, "Removed.")}>Remove</Btn>
</>
)}
</div>
</div>
)}
</li>
))}
</ul>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,70 @@
"use client";
/**
* Linked products (§8, §9): the church's other sites as the Hub lists them. Accounts is how
* people sign in here (the Website links to it by itself). With Cross Events (and later the App),
* events flow either way: "Show events from" brings its events here, read-only and linking back
* for registering; "Publish my events" offers this site's simple events to them.
*/
import { api, canEdit } from "@/admin/api";
import { Btn, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Product = { installId: string; product: string; url: string; connected: boolean; listed: boolean; showEvents: boolean | null; events: number; lastSyncAt: string | null; lastSyncError: string | null };
const NAMES: Record<string, string> = { accounts: "Accounts (sign-in)", events: "Cross Events", app: "Church App", website: "Website" };
export default function Linked() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<{ publishMyEvents: boolean; products: Product[] }>("/links");
const { busy, message, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const manager = ["owner", "admin"].includes(me.data.user.role);
return (
<>
<Title sub="Your church's other sites. Events can flow between them in either direction.">Linked products</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title="Publish my events">
<label className="flex items-start gap-3">
<input type="checkbox" className="mt-1" checked={data.publishMyEvents} disabled={!editor || busy}
onChange={(e) => run(async () => { await api("/feed", { method: "PUT", body: { publish: e.target.checked } }); await reload(); }, "Saved.")} />
<span>Offer the events you make here to your church&apos;s other sites (Cross Events, the App). They show them as read-only copies that link back here.</span>
</label>
</Panel>
{data.products.length === 0 && <Notice>No other sites yet. When your church has Cross Events or the App, they show here within 15 minutes.</Notice>}
{data.products.map((p) => (
<Panel key={p.installId}>
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h2 className="text-lg font-semibold">{NAMES[p.product] ?? p.product}</h2>
<a href={p.url} className="text-sm text-brand-text underline-offset-4 hover:underline" rel="noopener">{p.url}</a>
<p className="mt-1 text-sm">{p.connected ? <span className="text-green-800">Connected</span> : <span className="text-gray-600">Not connected</span>}</p>
</div>
{manager && !p.connected && p.listed && <Btn kind="primary" busy={busy} onClick={() => run(async () => { await api(`/links/${p.installId}/connect`, { body: {} }); await reload(); }, "Connected.")}>Connect</Btn>}
{manager && p.connected && p.product !== "accounts" && <Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/links/${p.installId}`, { method: "DELETE" }); await reload(); }, "Disconnected: its events are gone from here.")}>Disconnect</Btn>}
</div>
{p.product === "accounts" && p.connected && <p className="mt-3 text-sm text-gray-600">People sign in to this website&apos;s admin through it. This link stays.</p>}
{p.connected && p.product !== "accounts" && (
<div className="mt-4 space-y-2 border-t border-gray-200 pt-4">
<label className="flex items-center gap-3">
<input type="checkbox" checked={!!p.showEvents} disabled={!editor || busy}
onChange={(e) => run(async () => { await api(`/links/${p.installId}`, { method: "PUT", body: { showEvents: e.target.checked } }); await reload(); }, e.target.checked ? "Its events show here now." : "Its events are gone from here.")} />
<span>Show events from {NAMES[p.product]} on this website</span>
</label>
{p.showEvents && (
<p className="text-sm text-gray-600">
{p.events} {p.events === 1 ? "event" : "events"} from it{p.lastSyncAt && `, last checked ${when(p.lastSyncAt)}`}.{" "}
{editor && <Btn kind="link" onClick={() => run(async () => { await api(`/links/${p.installId}/sync`, { body: {} }); await reload(); }, "Checked.")}>Check now</Btn>}
</p>
)}
{p.lastSyncError && <Notice tone="warning">Last time: {p.lastSyncError}. The events from before keep showing.</Notice>}
</div>
)}
</Panel>
))}
</div>
</>
);
}
@@ -3,14 +3,17 @@
import { useState } from "react";
import { api } from "@/admin/api";
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
export default function Media() {
const { data, error, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>("/media");
const { data, error, reload } = useAdmin<{ storage: Storage; request: { at: string; steps: number } | null; items: MediaItem[] }>("/media");
const me = useAdmin<{ user: { role: string } }>("/me");
const [alts, setAlts] = useState<Record<string, string>>({});
const [steps, setSteps] = useState(1);
const { busy, message, run } = useAction();
if (!data) return <Loading error={error} />;
const manager = ["owner", "admin"].includes(me.data?.user.role ?? "");
const s = data.storage;
return (
<>
@@ -38,7 +41,22 @@ export default function Media() {
<div className="space-y-6">
<Panel title="Storage">
<StorageMeter s={s} />
{s.percent >= 80 && <div className="mt-3"><Notice tone={s.full ? "error" : "warning"}>{s.full ? "Storage is full: uploads have stopped until more storage is added." : "Storage is nearly full."} More comes in 5 GB steps (R20 a month each): contact Cross Code.</Notice></div>}
{s.percent >= 80 && <div className="mt-3"><Notice tone={s.full ? "error" : "warning"}>{s.full ? "Storage is full: uploads have stopped until more storage is added." : "Storage is nearly full."} Everything already uploaded keeps showing.</Notice></div>}
<div className="mt-4 border-t border-gray-200 pt-4">
<h3 className="font-semibold">Get more storage</h3>
<p className="mt-1 text-sm text-gray-600">In steps of 5 GB, R20 a month each, added to your church&apos;s account.</p>
{data.request ? (
<div className="mt-3"><Notice tone="info">You asked for {data.request.steps * 5} GB more on {when(data.request.at)}. Cross Code adds it to your account; uploads work again within a minute of that.</Notice></div>
) : manager ? (
<div className="mt-3 flex flex-wrap items-center gap-2">
<label className="text-sm" htmlFor="steps">Add</label>
<select id="steps" className={`${inputClass} w-28`} value={steps} onChange={(e) => setSteps(Number(e.target.value))}>
{[1, 2, 3, 4].map((n) => <option key={n} value={n}>{n * 5} GB</option>)}
</select>
<Btn kind="primary" busy={busy} onClick={() => run(async () => { await api("/storage-request", { body: { steps } }); await reload(); }, "Asked: Cross Code will add it.")}>Ask for it</Btn>
</div>
) : <p className="mt-2 text-sm text-gray-600">Your website&apos;s Owner or an Admin can ask for it.</p>}
</div>
</Panel>
<Panel title="Upload a photo">
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />}
@@ -0,0 +1,110 @@
"use client";
/**
* Messages (§7): from the church's YouTube channel or playlist automatically, or added by hand with
* a YouTube or Spotify link. Each publishes on its own (decision 9); ones from YouTube go live by
* themselves. Add the speaker, series and passage afterwards, or hide one.
*/
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Message = { id: string; title: string; date: string; mediaUrl: string; source: string; speaker: string | null; passage: string | null; notes: string | null; series: string | null; hidden: boolean; published: boolean; thumbnail: string | null };
type Data = { youtube: { source: { kind: string; id: string } | null; lastSync: string | null; lastError: string | null }; items: Message[] };
const blank = { title: "", date: new Date().toISOString().slice(0, 10), mediaUrl: "", speaker: "", passage: "", series: "", notes: "", hidden: false };
function MessageForm({ initial, fromFeed, onSave, onCancel }: { initial: typeof blank; fromFeed: boolean; onSave: (v: typeof blank) => Promise<unknown>; onCancel: () => void }) {
const [v, setV] = useState(initial);
const { busy, message, fields, run } = useAction();
const set = (k: keyof typeof blank, x: string | boolean) => setV({ ...v, [k]: x });
return (
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Title" error={fields.title}><input className={inputClass} value={v.title} maxLength={500} onChange={(e) => set("title", e.target.value)} /></Field>
<Field label="Date" error={fields.date}><input type="date" className={inputClass} value={v.date.slice(0, 10)} onChange={(e) => set("date", e.target.value)} /></Field>
{!fromFeed && <Field label="YouTube or Spotify link" hint="A video (youtube.com/watch?v=…, youtu.be/…) or a Spotify episode." error={fields.mediaUrl}><input className={inputClass} value={v.mediaUrl} onChange={(e) => set("mediaUrl", e.target.value)} /></Field>}
<Field label="Speaker" error={fields.speaker}><input className={inputClass} value={v.speaker} maxLength={300} onChange={(e) => set("speaker", e.target.value)} /></Field>
<Field label="Series" hint="Messages with the same series name are grouped." error={fields.series}><input className={inputClass} value={v.series} maxLength={300} onChange={(e) => set("series", e.target.value)} /></Field>
<Field label="Bible passage" error={fields.passage}><input className={inputClass} value={v.passage} maxLength={300} onChange={(e) => set("passage", e.target.value)} /></Field>
</div>
<Field label="Notes" error={fields.notes}><textarea className={inputClass} rows={3} value={v.notes} maxLength={8000} onChange={(e) => set("notes", e.target.value)} /></Field>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={v.hidden} onChange={(e) => set("hidden", e.target.checked)} />Hide it from the site</label>
<div className="flex gap-2"><Btn kind="primary" busy={busy} onClick={() => run(() => onSave(v))}>Save</Btn><Btn onClick={onCancel}>Cancel</Btn></div>
{message && <Notice tone={message.tone}>{message.text}</Notice>}
</div>
);
}
export default function Messages() {
const me = useAdmin<{ user: { role: string } }>("/me");
const { data, error, reload } = useAdmin<Data>("/messages");
const [editing, setEditing] = useState<string | null>(null);
const [youtube, setYoutube] = useState<string | null>(null);
const { busy, message, fields, run } = useAction();
if (!data || !me.data) return <Loading error={error ?? me.error} />;
const editor = canEdit(me.data.user.role);
const body = (v: typeof blank) => ({ ...v, date: v.date, speaker: v.speaker || null, passage: v.passage || null, series: v.series || null, notes: v.notes || null });
const yt = data.youtube;
return (
<>
<Title sub="Sermons. Audio and video stay on YouTube or Spotify: nothing is uploaded.">Messages</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="space-y-6">
<Panel title="From YouTube, automatically">
<p className="mb-3 text-sm text-gray-600">Each new video becomes a message within the hour. A playlist is better when your channel has other videos too.</p>
<div className="flex flex-wrap items-end gap-3">
<div className="min-w-[18rem] flex-1">
<Field label="Channel id or playlist link" hint="Your channel id starts with UC: on YouTube, open Settings → Advanced settings. Or paste a playlist's address." error={fields.youtube}>
<input className={inputClass} value={youtube ?? (yt.source ? (yt.source.kind === "playlist" ? `https://www.youtube.com/playlist?list=${yt.source.id}` : yt.source.id) : "")} disabled={!editor} onChange={(e) => setYoutube(e.target.value)} />
</Field>
</div>
{editor && <Btn kind="primary" busy={busy} onClick={() => run(async () => { const r = await api<{ sync: { added: number } | null }>("/messages-youtube", { method: "PUT", body: { youtube: youtube ?? "" } }); setYoutube(null); await reload(); return r; }, "Saved. New videos come in every hour.")}>Save</Btn>}
{editor && yt.source && <Btn busy={busy} onClick={() => run(async () => { await api("/messages-youtube/sync", { body: {} }); await reload(); }, "Checked YouTube.")}>Check now</Btn>}
</div>
{yt.lastSync && <p className="mt-2 text-xs text-gray-500">Last checked {when(yt.lastSync)}</p>}
{yt.lastError && <div className="mt-2"><Notice tone="warning">YouTube couldn&apos;t be reached last time: {yt.lastError.replace(/^\S+\s/, "")}</Notice></div>}
</Panel>
{editor && (
<Panel title="Add one by hand">
{editing === "new"
? <MessageForm initial={blank} fromFeed={false} onCancel={() => setEditing(null)} onSave={async (v) => { await api("/messages", { body: body(v) }); setEditing(null); await reload(); }} />
: <Btn kind="primary" onClick={() => setEditing("new")}>Add a message</Btn>}
</Panel>
)}
<Panel title="All messages">
{data.items.length === 0 && <p className="text-gray-600">None yet.</p>}
<ul className="divide-y divide-gray-200">
{data.items.map((m) => (
<li key={m.id} className="py-3">
{editing === m.id ? (
<MessageForm fromFeed={m.source === "youtube_feed"} onCancel={() => setEditing(null)}
initial={{ title: m.title, date: m.date.slice(0, 10), mediaUrl: m.mediaUrl, speaker: m.speaker ?? "", passage: m.passage ?? "", series: m.series ?? "", notes: m.notes ?? "", hidden: m.hidden }}
onSave={async (v) => { await api(`/messages/${m.id}`, { method: "PUT", body: body(v) }); setEditing(null); await reload(); }} />
) : (
<div className="flex flex-wrap items-center gap-4">
{m.thumbnail ? <img src={m.thumbnail} alt="" className="h-14 w-24 rounded object-cover" /> : <div className="h-14 w-24 rounded bg-gray-100" />}
<div className="min-w-0 flex-1">
<p className="font-medium">{m.title}</p>
<p className="text-sm text-gray-600">{[when(m.date).split(",")[0], m.speaker, m.series, m.source === "youtube_feed" ? "from YouTube" : m.source === "spotify" ? "Spotify" : "YouTube"].filter(Boolean).join(" · ")}</p>
<p className="text-xs">{m.hidden ? <span className="text-amber-800">Hidden</span> : m.published ? <span className="text-green-800">On the site</span> : <span className="text-gray-500">Not published</span>}</p>
</div>
{editor && (
<div className="flex flex-wrap gap-2">
<Btn onClick={() => setEditing(m.id)}>Edit</Btn>
<Btn busy={busy} onClick={() => run(async () => { await api(`/messages/${m.id}/publish`, { body: { live: !m.published } }); await reload(); }, m.published ? "Taken off the site." : "On the site now.")}>{m.published ? "Unpublish" : "Publish"}</Btn>
{m.source !== "youtube_feed" && <Btn kind="danger" busy={busy} onClick={() => run(async () => { await api(`/messages/${m.id}`, { method: "DELETE" }); await reload(); }, "Removed.")}>Remove</Btn>}
</div>
)}
</div>
)}
</li>
))}
</ul>
</Panel>
</div>
</>
);
}
@@ -10,6 +10,7 @@ type Overview = {
storage: Storage;
colourNotes: string[];
checklist: { key: string; label: string; done: boolean; href: string | null }[];
recent: { at: string; who: string; action: string; detail: string | null }[];
};
/** The dashboard (§10): the setup checklist, what's waiting to be published, storage. */
@@ -37,6 +38,13 @@ export default function Dashboard() {
<p>{data.pending} {data.pending === 1 ? "change" : "changes"}. <Link href="/admin/publish" className="font-semibold text-brand-text underline-offset-4 hover:underline">Review and publish</Link></p>
) : <p className="text-gray-600">Nothing: the site shows everything you&apos;ve done.</p>}
</Panel>
<Panel title="Recent edits">
{data.recent.length === 0 ? <p className="text-gray-600">None yet.</p> : (
<ul className="space-y-2 text-sm">
{data.recent.map((e, i) => <li key={i}><span className="font-medium">{e.who}</span> {e.action.charAt(0).toLowerCase() + e.action.slice(1)}{e.detail && <>: {e.detail}</>} <span className="text-gray-500">({when(e.at)})</span></li>)}
</ul>
)}
</Panel>
<Panel title="Storage"><StorageMeter s={data.storage} /></Panel>
{data.colourNotes.length > 0 && (
<Notice tone="info"><p className="font-semibold">About your colours</p><ul className="mt-1 list-disc pl-5">{data.colourNotes.map((n) => <li key={n}>{n}</li>)}</ul></Notice>
@@ -12,8 +12,8 @@ import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
import { ImagePicker } from "@/admin/media";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown> };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; sections: Section[] };
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string };
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] };
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
const LISTS: Record<string, string> = {
@@ -55,7 +55,7 @@ export default function EditPage() {
if (!page) return <Loading error={error} />;
const f = { ...page, ...form };
const saveDetails = () => details.run(async () => {
const p = await api<PageData>(`/pages/${id}`, { method: "PUT", body: { title: f.title, slug: f.slug, seoTitle: f.seoTitle, description: f.description, navLabel: f.navLabel, inNav: f.inNav, imageId: f.imageId } });
const p = await api<PageData>(`/pages/${id}`, { method: "PUT", body: { title: f.title, slug: f.slug, seoTitle: f.seoTitle, description: f.description, navLabel: f.navLabel, inNav: f.inNav, imageId: f.imageId, ifUpdatedAt: page.updatedAt } });
setData(p);
setForm(null);
}, "Saved as a draft.");
@@ -97,7 +97,7 @@ export default function EditPage() {
{HOME_ORDER.map((type) => {
const s = page.sections.find((x) => x.type === type);
const spec = SECTION_FIELDS[type]!;
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data } }))} />;
return <SectionEditor key={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
})}
</>
) : (
@@ -108,7 +108,7 @@ export default function EditPage() {
if (!spec) return null;
return (
<SectionEditor key={s.id} title={`${spec.name}${s.hidden ? " (hidden)" : ""}`} fields={spec.fields} initial={s.data}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data } }))}
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
extra={<>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "up" })} disabled={i === 0} aria-label="Move up">↑</Btn>
<Btn onClick={() => blockCall(`/blocks/${s.id}/move`, "POST", { direction: "down" })} disabled={i === page.sections.length - 1} aria-label="Move down">↓</Btn>
@@ -0,0 +1,104 @@
"use client";
/**
* People (§10): who can use this website's admin, and as what. Adding someone by email gives them
* an account at the church's sign-in if they have none (they get an email to choose a password).
*/
import { useState } from "react";
import { api, ROLE_NAMES } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
type Person = { id: string; name: string; email: string; role: string; ministryId: string | null; ministry: string | null; lastSignInAt: string | null };
const ROLE_TEXT: Record<string, string> = {
owner: "Everything, including who is Owner",
admin: "Everything but Owners",
editor: "Edits everything and publishes",
ministry_leader: "Edits their own ministry; an Editor publishes it",
viewer: "Looks, changes nothing",
};
function RolePicker({ role, ministryId, onChange, ministries, canOwner, errors }: { role: string; ministryId: string | null; onChange: (r: string, m: string | null) => void; ministries: { id: string; name: string }[]; canOwner: boolean; errors: Record<string, string> }) {
return (
<div className="grid gap-3 sm:grid-cols-2">
<Field label="Role" hint={ROLE_TEXT[role]} error={errors.role}>
<select className={inputClass} value={role} onChange={(e) => onChange(e.target.value, ministryId)}>
{Object.keys(ROLE_TEXT).filter((r) => canOwner || r !== "owner").map((r) => <option key={r} value={r}>{ROLE_NAMES[r]}</option>)}
</select>
</Field>
{role === "ministry_leader" && (
<Field label="Their ministry" error={errors.ministryId}>
<select className={inputClass} value={ministryId ?? ""} onChange={(e) => onChange(role, e.target.value || null)}>
<option value="">Choose…</option>
{ministries.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
</select>
</Field>
)}
</div>
);
}
export default function People() {
const me = useAdmin<{ user: { id: string; role: string } }>("/me");
const list = useAdmin<Person[]>("/people");
const ministries = useAdmin<{ id: string; name: string }[]>("/ministries");
const [add, setAdd] = useState({ name: "", email: "", role: "editor", ministryId: null as string | null });
const [editing, setEditing] = useState<{ id: string; role: string; ministryId: string | null } | null>(null);
const { busy, message, fields, run } = useAction();
if (!list.data || !me.data) return <Loading error={list.error ?? me.error} />;
const owner = me.data.user.role === "owner";
const mayTouch = (p: Person) => p.id !== me.data!.user.id && (owner || p.role !== "owner");
return (
<>
<Title sub="Who can use this website's admin. They sign in with their church account.">People</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<div className="grid gap-6 lg:grid-cols-[3fr_2fr]">
<Panel>
<ul className="divide-y divide-gray-200">
{list.data.map((p) => (
<li key={p.id} className="py-3">
{editing?.id === p.id ? (
<div className="space-y-3">
<p className="font-medium">{p.name}</p>
<RolePicker role={editing.role} ministryId={editing.ministryId} ministries={ministries.data ?? []} canOwner={owner} errors={fields} onChange={(role, ministryId) => setEditing({ ...editing, role, ministryId })} />
<div className="flex gap-2">
<Btn kind="primary" busy={busy} onClick={() => run(async () => { await api(`/people/${p.id}`, { method: "PUT", body: { role: editing.role, ministryId: editing.ministryId } }); setEditing(null); await list.reload(); }, "Saved. A lower role takes effect at once.")}>Save</Btn>
<Btn onClick={() => setEditing(null)}>Cancel</Btn>
</div>
</div>
) : (
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<p className="font-medium">{p.name}{p.id === me.data!.user.id && " (you)"}</p>
<p className="text-sm text-gray-600">{p.email} · {ROLE_NAMES[p.role]}{p.ministry && ` of ${p.ministry}`}</p>
<p className="text-xs text-gray-500">{p.lastSignInAt ? `Last signed in ${when(p.lastSignInAt)}` : "Hasn't signed in yet"}</p>
</div>
{mayTouch(p) && (
<div className="flex gap-2">
<Btn onClick={() => setEditing({ id: p.id, role: p.role, ministryId: p.ministryId })}>Change role</Btn>
<Btn kind="danger" onClick={() => run(async () => { await api(`/people/${p.id}`, { method: "DELETE" }); await list.reload(); }, `${p.name} no longer has access.`)}>Remove</Btn>
</div>
)}
</div>
)}
</li>
))}
</ul>
</Panel>
<Panel title="Add someone">
<div className="space-y-3">
<Field label="Name" error={fields.name}><input className={inputClass} value={add.name} maxLength={200} onChange={(e) => setAdd({ ...add, name: e.target.value })} /></Field>
<Field label="Email" hint="If they have no church account yet, they get an email to choose a password." error={fields.email}><input type="email" className={inputClass} value={add.email} onChange={(e) => setAdd({ ...add, email: e.target.value })} /></Field>
<RolePicker role={add.role} ministryId={add.ministryId} ministries={ministries.data ?? []} canOwner={owner} errors={fields} onChange={(role, ministryId) => setAdd({ ...add, role, ministryId })} />
<Btn kind="primary" busy={busy} disabled={!add.name || !add.email} onClick={() => run(async () => {
const r = await api<{ newAccount: boolean }>("/people", { body: add });
setAdd({ name: "", email: "", role: "editor", ministryId: null });
await list.reload();
return r;
}, "Added. They can sign in now.")}>Add</Btn>
</div>
</Panel>
</div>
</>
);
}
@@ -0,0 +1,69 @@
"use client";
/**
* Settings (§10): the Coming soon line, search engine verification (live at once), and the menu's
* order (a draft, published with the site).
*/
import Link from "next/link";
import { useState } from "react";
import { api, canEdit } from "@/admin/api";
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
type Settings = { comingSoonText: string; googleVerification: string | null; bingVerification: string | null };
type PageRow = { id: string; kind: string; title: string; inNav: boolean };
export default function SettingsPage() {
const me = useAdmin<{ user: { role: string } }>("/me");
const settings = useAdmin<Settings>("/settings");
const pages = useAdmin<PageRow[]>("/pages");
const [form, setForm] = useState<Partial<Settings>>({});
const { busy, message, fields, run } = useAction();
if (!settings.data || !pages.data || !me.data) return <Loading error={settings.error ?? pages.error} />;
const editor = canEdit(me.data.user.role);
const s = { ...settings.data, ...form };
const menu = pages.data.filter((p) => p.kind !== "home");
const move = (i: number, d: -1 | 1) => run(async () => {
const list = [...menu];
[list[i], list[i + d]] = [list[i + d]!, list[i]!];
await api("/pages-order", { method: "PUT", body: { ids: list.map((p) => p.id) } });
await pages.reload();
}, "Saved as a draft: publish to change the menu.");
return (
<>
<Title sub="How your site is found, and its menu.">Settings</Title>
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
<fieldset disabled={!editor} className="space-y-6">
<Panel title="Search engines">
<p className="mb-3 text-sm text-gray-600">To see how people find your site, add it to Google Search Console and Bing Webmaster Tools. They give you a code to prove the site is yours: paste it here (the whole tag is fine), save, then press Verify there. This goes live straight away.</p>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Google Search Console code" error={fields.googleVerification}><input className={inputClass} value={s.googleVerification ?? ""} onChange={(e) => setForm({ ...form, googleVerification: e.target.value })} /></Field>
<Field label="Bing Webmaster Tools code" error={fields.bingVerification}><input className={inputClass} value={s.bingVerification ?? ""} onChange={(e) => setForm({ ...form, bingVerification: e.target.value })} /></Field>
</div>
<p className="mt-3 text-sm text-gray-600">A Google Business Profile helps people find your church on Google Maps: set one up at business.google.com with the same address as your church details.</p>
</Panel>
<Panel title="Coming soon">
<Field label="The line under “Coming soon”" hint="Shown until you first publish your site." error={fields.comingSoonText}>
<input className={inputClass} value={s.comingSoonText} maxLength={300} onChange={(e) => setForm({ ...form, comingSoonText: e.target.value })} />
</Field>
</Panel>
{editor && Object.keys(form).length > 0 && (
<Btn kind="primary" busy={busy} onClick={() => run(async () => { settings.setData(await api<Settings>("/settings", { method: "PUT", body: form })); setForm({}); }, "Saved.")}>Save settings</Btn>
)}
<Panel title="Menu order">
<p className="mb-3 text-sm text-gray-600">Pages in the menu, in this order. Which pages show is set on each page (<Link href="/admin/pages" className="underline">Pages</Link>).</p>
<ul className="divide-y divide-gray-200">
{menu.map((p, i) => (
<li key={p.id} className="flex items-center justify-between gap-3 py-2">
<span>{p.title}{!p.inNav && <span className="text-sm text-gray-500"> (not in the menu)</span>}</span>
<span className="flex gap-1">
<Btn onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${p.title} up`}>↑</Btn>
<Btn onClick={() => move(i, 1)} disabled={busy || i === menu.length - 1} aria-label={`Move ${p.title} down`}>↓</Btn>
</span>
</li>
))}
</ul>
</Panel>
</fieldset>
</>
);
}
@@ -64,12 +64,16 @@ export default function TemplatePage() {
<Panel title="Template">
<div className="grid gap-3 sm:grid-cols-2">
{TEMPLATES.map((t) => (
<button key={t.id} type="button" disabled={busy} onClick={() => t.id !== design.template && save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}
aria-pressed={t.id === design.template}
className={cx("rounded-lg border-2 p-4 text-left", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200 hover:border-gray-400")}>
<div key={t.id} className={cx("rounded-lg border-2 p-4", t.id === design.template ? "border-brand bg-brand-tint" : "border-gray-200")}>
<span className="block font-semibold">{t.name}{t.id === design.template && " (in use)"}</span>
<span className="mt-1 block text-sm text-gray-600">{t.text}</span>
</button>
{t.id !== design.template && (
<div className="mt-3 flex flex-wrap gap-2">
<a href={`/preview/start?template=${t.id}`} className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-semibold hover:bg-gray-50">Preview with your content</a>
<Btn busy={busy} onClick={() => save({ template: t.id }, `Switched to ${t.name}. Your own choices are kept; the rest moved to ${t.name}'s defaults.`)}>Use {t.name}</Btn>
</div>
)}
</div>
))}
</div>
</Panel>
@@ -16,6 +16,11 @@ const PROBLEMS: Record<string, { title: string; text: string; retry: boolean }>
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_NOT_LINKED: {
title: "This website isn't linked to your church's sign-in yet",
text: "It links by itself shortly after it's installed. Please try again in a minute. If this keeps happening, contact Cross Code.",
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.",
@@ -2,21 +2,26 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { loadPublished } from "@/site/load";
import { fmtDate, fmtTime, Img } from "@/site/parts";
import { siteBase } from "@/site/meta";
import { breadcrumbLd, eventLd, shareImage, siteBase } from "@/site/meta";
import { Shell } from "@/site/Shell";
type Props = { params: Promise<{ slug: string }> };
async function find(slug: string) {
const site = await loadPublished();
const event = site?.events.find((e) => e.from === "website" && e.url === `/events/${slug}`) ?? null;
const event = site?.events.find((e) => e.from === "website" && e.slug === slug) ?? null;
return { site, event };
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { site, event } = await find((await params).slug);
if (!site || !event) return { robots: { index: false } };
return { metadataBase: siteBase(site), title: event.title, description: event.summary ?? undefined, alternates: { canonical: event.url } };
const path = `/events/${event.slug}`;
const image = event.image && !event.image.url.endsWith(".svg") ? { url: event.image.url, alt: event.image.alt } : { url: shareImage(event.title), width: 1200, height: 630, alt: event.title };
return {
metadataBase: siteBase(site), title: event.title, description: event.summary ?? undefined, alternates: { canonical: path },
openGraph: { type: "website", title: event.title, description: event.summary ?? undefined, url: path, images: [image] }, twitter: { card: "summary_large_image" },
};
}
/** A simple event made in the Website (§8). Cross Events' own events link to Cross Events instead. */
@@ -25,8 +30,11 @@ export default async function EventPage({ params }: Props) {
if (!site || !event) notFound();
const zone = site.church?.timezone ?? "Africa/Johannesburg";
const events = site.snapshot.pages.find((p) => p.kind === "events");
const path = `/events/${event.slug}`;
const lds = [eventLd(site, { ...event, url: path }), breadcrumbLd(site, [...(events ? [{ name: events.title, path: events.path }] : []), { name: event.title, path }])];
return (
<Shell site={site} path={event.url}>
<Shell site={site} path={path}>
{lds.map((ld, i) => <script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />)}
<article className="cc-section">
<div className="cc-wrap grid gap-10 md:grid-cols-2">
<Img image={event.image} priority />
@@ -35,7 +43,8 @@ export default async function EventPage({ params }: Props) {
<h1 className="cc-h1 mt-2">{event.title}</h1>
{event.location && <p className="cc-muted mt-3 text-lg">{event.location}</p>}
{event.summary && <p className="cc-prose mt-6">{event.summary}</p>}
{events && <a href={events.path} className="cc-link mt-8 inline-block font-semibold">All events</a>}
{event.link && <a href={event.link} rel="noopener" className="cc-btn mt-8">More information</a>}
{events && <a href={events.path} className="cc-link mt-8 block font-semibold">All events</a>}
</div>
</div>
</article>
+6 -2
View File
@@ -66,11 +66,15 @@ h1, h2, h3 {
/* Text on a dark background (Bold's cards and bands, a dark section): light, and still AA. */
.cc-dark .cc-muted, [data-template="bold"] .cc-card .cc-muted,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-muted { color: rgb(255 255 255 / 0.8); }
.cc-dark .cc-link, .cc-dark .cc-eyebrow, [data-template="bold"] .cc-card .cc-link, [data-template="bold"] .cc-card .cc-eyebrow,
.cc-dark .cc-link, .cc-dark .cc-eyebrow, .cc-dark .cc-brand-text,
[data-template="bold"] .cc-card .cc-link, [data-template="bold"] .cc-card .cc-eyebrow, [data-template="bold"] .cc-card .cc-brand-text,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-link,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-eyebrow { color: rgb(255 255 255); }
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-eyebrow,
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-brand-text { color: rgb(255 255 255); }
.cc-muted { color: rgb(75 85 99); }
/* The church's colour as text (made AA on light by the palette): here, not a utility, so the dark rules above win. */
.cc-brand-text { color: rgb(var(--brand-text)); }
.cc-link { color: rgb(var(--brand-text)); @apply underline-offset-4 hover:underline; }
.cc-eyebrow { @apply text-sm font-semibold uppercase tracking-widest; color: rgb(var(--brand-text)); }
[data-template="heritage"] .cc-eyebrow { @apply font-normal tracking-[0.25em]; font-variant: small-caps; text-transform: none; }
+4 -1
View File
@@ -13,7 +13,10 @@ export async function generateMetadata(): Promise<Metadata> {
return { title: { absolute: c.church ? `${c.church.name}: coming soon` : "Coming soon" }, robots: { index: false, follow: true } };
}
const home = c.snapshot.pages.find((p) => p.kind === "home");
return home ? pageMetadata(c, home) : {};
// Search Console and Bing Webmaster Tools look for their code on the home page (Settings).
const v = c.verification;
const verification = v && (v.google || v.bing) ? { verification: { ...(v.google ? { google: v.google } : {}), ...(v.bing ? { other: { "msvalidate.01": v.bing } } : {}) } } : {};
return home ? { ...pageMetadata(c, home), ...verification } : verification;
}
export default async function Home() {
@@ -1,12 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { localRedirect } from "@/lib/localRedirect";
/**
* A shared preview link (§4): keeps its token in a cookie for the rest of the visit, so every page
* shows the working copy. The backend checks the token (7 days, until revoked) on every page.
*/
export async function GET(request: NextRequest, { params }: { params: Promise<{ token: string }> }) {
export async function GET(_request: NextRequest, { params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
const res = NextResponse.redirect(new URL("/", request.url), 303);
const res = localRedirect("/");
if (/^[A-Za-z0-9_-]{20,100}$/.test(token)) {
res.cookies.set("ccw_preview", token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: 7 * 86400 });
}
@@ -1,10 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { localRedirect } from "@/lib/localRedirect";
/** Leaves the preview: an admin goes back to editing, someone with a shared link to the live site. */
export function GET(request: NextRequest) {
const admin = request.cookies.get("ccw_preview")?.value === "admin";
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : "/admin") : "/";
const res = NextResponse.redirect(new URL(to, request.url), 303);
const trying = !!request.cookies.get("ccw_preview_template")?.value;
const to = admin ? (request.nextUrl.searchParams.get("published") ? "/admin/publish" : trying ? "/admin/template" : "/admin") : "/";
const res = localRedirect(to);
res.cookies.delete("ccw_preview");
res.cookies.delete("ccw_preview_template");
return res;
}
@@ -1,4 +1,5 @@
import { NextResponse, type NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { localRedirect } from "@/lib/localRedirect";
/**
* Preview (WEBSITE-1.0-PLAN §4): a signed-in admin sees the working copy on the site's own
@@ -6,7 +7,12 @@ import { NextResponse, type NextRequest } from "next/server";
* on every page (site/preview), so it shows nothing to anyone else.
*/
export function GET(request: NextRequest) {
const res = NextResponse.redirect(new URL("/", request.url), 303);
res.cookies.set("ccw_preview", "admin", { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/" });
const res = localRedirect("/");
const opts = { httpOnly: true, sameSite: "lax" as const, secure: process.env.NODE_ENV === "production", path: "/" };
res.cookies.set("ccw_preview", "admin", opts);
// "Choose your template": the church's own content in another template, nothing saved.
const template = request.nextUrl.searchParams.get("template");
if (template && /^(heritage|bold|community|clean)$/.test(template)) res.cookies.set("ccw_preview_template", template, opts);
else res.cookies.delete("ccw_preview_template");
return res;
}
@@ -0,0 +1,29 @@
import { ImageResponse } from "next/og";
import type { NextRequest } from "next/server";
import { loadContent } from "@/site/load";
/**
* The share image for a page without its own (ROADMAP-v3 §11: "Pages without their own image get a
* share image generated from the church's logo and colours"): 1200 × 630, the church's colour, its
* name and the page's title. `?t=` is the title (only shown, never trusted for anything else).
*/
export async function GET(request: NextRequest) {
const c = await loadContent();
const title = (request.nextUrl.searchParams.get("t") ?? "").slice(0, 90);
const name = c.church?.name ?? "Our church";
const rgb = (triple: string) => `rgb(${triple.split(" ").join(",")})`;
const logo = c.church?.branding.logoUrl;
return new ImageResponse(
(
<div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", justifyContent: "space-between", padding: 72, background: rgb(c.palette.brand), color: rgb(c.palette.onBrand) }}>
<div style={{ display: "flex", alignItems: "center", gap: 24 }}>
{logo && /^https:\/\//.test(logo) && !logo.endsWith(".svg") ? <img src={logo} alt="" height={88} style={{ borderRadius: 12, background: "white", padding: 8 }} /> : null}
<div style={{ fontSize: 40, fontWeight: 700 }}>{name}</div>
</div>
<div style={{ display: "flex", fontSize: title.length > 40 ? 64 : 80, fontWeight: 800, lineHeight: 1.1 }}>{title || name}</div>
<div style={{ display: "flex", height: 12, width: 220, background: rgb(c.palette.accent), borderRadius: 6 }} />
</div>
),
{ width: 1200, height: 630, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
+1 -1
View File
@@ -14,6 +14,6 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const at = (path: string) => new URL(path, base).toString();
return [
...c.snapshot.pages.map((p) => ({ url: at(p.path), changeFrequency: "weekly" as const, priority: p.kind === "home" ? 1 : 0.7 })),
...c.events.filter((e) => e.from === "website" && e.url.startsWith("/")).map((e) => ({ url: at(e.url), changeFrequency: "weekly" as const, priority: 0.5 })),
...c.events.filter((e) => e.from === "website" && e.slug).map((e) => ({ url: at(`/events/${e.slug}`), changeFrequency: "weekly" as const, priority: 0.5 })),
];
}
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
/**
* 1.0.2: a 303 to a page of this site with a relative Location ("/admin"), so the browser stays on the
* address it's on. `new URL(path, request.url)` used the address the request reached Next.js on,
* which behind the proxy is the server's own (http://localhost:<web port>): Preview sent admins there.
*/
export function localRedirect(path: string): NextResponse {
if (!path.startsWith("/") || path.startsWith("//")) throw new Error(`Not a path on this site: ${path}`);
return new NextResponse(null, { status: 303, headers: { Location: path } });
}
@@ -0,0 +1,32 @@
"use client";
import { useEffect, useRef, useState } from "react";
/**
* The OpenStreetMap embed, loaded only once it's on screen (no Google, no cookies). An iframe's own
* `loading="lazy"` loads anything within about 1,250px of the screen, so on a phone the map
* (300 KB of OpenStreetMap's script) loaded with the page and slowed it down (Lighthouse,
* WEBSITE-1.0-PLAN §13), and OpenStreetMap saw every visitor. Until then: a link to the map.
*/
export function LazyMap({ src, href }: { src: string; href: string | null }) {
const box = useRef<HTMLDivElement>(null);
const [show, setShow] = useState(false);
useEffect(() => {
const el = box.current;
if (!el || typeof IntersectionObserver === "undefined") { setShow(true); return; }
const io = new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) { setShow(true); io.disconnect(); }
}, { rootMargin: "100px" });
io.observe(el);
return () => io.disconnect();
}, []);
return (
<div ref={box} data-map className="cc-frame min-h-[18rem] bg-gray-100">
{show ? (
<iframe title="Map" className="h-full min-h-[18rem] w-full border-0" src={src} />
) : (
href && <a href={href} rel="noopener" className="flex h-full min-h-[18rem] items-center justify-center font-semibold text-gray-700 underline">Open the map</a>
)}
</div>
);
}
@@ -4,9 +4,11 @@ import { useState } from "react";
/**
* A message's video or audio, loaded only when clicked (WEBSITE-1.0-PLAN §7): a thumbnail first,
* then youtube-nocookie or Spotify's player. Nothing loads from YouTube or Spotify until then.
* then youtube-nocookie or Spotify's player. Nothing loads from YouTube or Spotify until then: the
* thumbnail is served by the site (`/api/thumbnails/<id>.jpg`, backend site/thumbnails.ts).
*/
export function MessagePlayer({ title, embedUrl, thumbnail, url, source, className }: { title: string; embedUrl: string | null; thumbnail: string | null; url: string; source: "youtube" | "spotify"; className?: string }) {
/** `priority`: the first thing on screen (the messages page's first message), so its thumbnail isn't lazy (it's the LCP image). */
export function MessagePlayer({ title, embedUrl, thumbnail, url, source, className, priority }: { title: string; embedUrl: string | null; thumbnail: string | null; url: string; source: "youtube" | "spotify"; className?: string; priority?: boolean }) {
const [playing, setPlaying] = useState(false);
const ratio = source === "spotify" ? "aspect-[16/7]" : "aspect-video";
if (playing && embedUrl) {
@@ -18,7 +20,7 @@ export function MessagePlayer({ title, embedUrl, thumbnail, url, source, classNa
}
return (
<div className={`cc-frame relative ${ratio} ${className ?? ""} bg-gray-900`}>
{thumbnail && <img src={thumbnail} alt="" className="cc-img absolute inset-0 opacity-80" loading="lazy" />}
{thumbnail && <img src={thumbnail} alt="" className="cc-img absolute inset-0 opacity-80" {...(priority ? { fetchPriority: "high" as const } : { loading: "lazy" as const })} />}
{embedUrl ? (
<button type="button" onClick={() => setPlaying(true)} className="absolute inset-0 flex items-center justify-center" aria-label={`Play ${title}`}>
<span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/95 text-gray-900 shadow-lg">
+9 -3
View File
@@ -2,6 +2,7 @@
* A page other than home (WEBSITE-1.0-PLAN §6): its title, what its kind lists (ministries,
* leaders, events, messages, contact details), then its blocks.
*/
import { preload } from "react-dom";
import { MessagePlayer } from "./MessagePlayer";
import { t } from "./load";
import { cx, DateBadge, dayName, fmtDate, Img, Paragraphs } from "./parts";
@@ -68,13 +69,17 @@ function Listing({ page, site }: { page: Page; site: Published }) {
</div>
</section>
);
case "messages":
case "messages": {
// The first thumbnail is the largest thing on screen (Lighthouse's LCP): ask for it from the
// <head>, rather than once the HTML has been read. Thumbnails come from the site itself.
const thumb = site.messages[0]?.thumbnail;
if (thumb) preload(thumb, { as: "image", fetchPriority: "high" });
return (
<section className="cc-section">
<div className="cc-wrap grid gap-10 sm:grid-cols-2">
{site.messages.map((m) => (
{site.messages.map((m, i) => (
<article key={m.slug} id={m.slug} className="scroll-mt-24">
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} />
<MessagePlayer title={m.title} embedUrl={m.embedUrl} thumbnail={m.thumbnail} url={m.url} source={m.source} priority={i === 0} />
{m.series && <p className="cc-eyebrow mt-4">{m.series}</p>}
<h2 className="cc-h3 mt-1">{m.title}</h2>
<p className="cc-muted text-sm">{[m.speaker, m.passage, fmtDate(m.date, zone, { day: "numeric", month: "long", year: "numeric" })].filter(Boolean).join(" · ")}</p>
@@ -83,6 +88,7 @@ function Listing({ page, site }: { page: Page; site: Published }) {
</div>
</section>
);
}
case "contact": {
const c = site.church;
if (!c) return null;
@@ -7,7 +7,7 @@
*/
import { useEffect, useState } from "react";
export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admin" | "link"; canPublish: boolean }; size?: "phone" | "tablet" | "desktop" }) {
export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admin" | "link"; canPublish: boolean; template?: string | null }; size?: "phone" | "tablet" | "desktop" }) {
const [inFrame, setInFrame] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -38,7 +38,7 @@ export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admi
return (
<div className="bg-gray-900 font-sans text-sm text-white" role="region" aria-label="Preview">
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-2">
<p><strong>Preview</strong> · {preview.by === "admin" ? "your changes, not live yet" : "not live yet"}</p>
<p><strong>Preview</strong> · {preview.template ? `your content in the ${preview.template[0]!.toUpperCase()}${preview.template.slice(1)} template (nothing saved)` : preview.by === "admin" ? "your changes, not live yet" : "not live yet"}</p>
<div className="flex items-center gap-1" aria-label="Width">
{width("phone", "Phone", "/preview/frame?size=phone")}
{width("tablet", "Tablet", "/preview/frame?size=tablet")}
@@ -47,7 +47,7 @@ export function PreviewBar({ preview, size = "desktop" }: { preview: { by: "admi
<div className="flex items-center gap-3">
{error && <span role="alert" className="text-amber-300">{error}</span>}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that clears the preview cookie: a full page load, not a client navigation */}
<a href="/preview/exit" className="underline-offset-4 hover:underline">{preview.by === "admin" ? "Back to editing" : "Leave the preview"}</a>
<a href="/preview/exit" className="underline-offset-4 hover:underline">{preview.template ? "Back to choosing" : preview.by === "admin" ? "Back to editing" : "Leave the preview"}</a>
{preview.canPublish && (
<button type="button" onClick={publish} disabled={busy} className="rounded bg-white px-3 py-1.5 font-semibold text-gray-900 disabled:opacity-60">{busy ? "Publishing…" : "Publish"}</button>
)}
+1
View File
@@ -30,6 +30,7 @@ export const loadContent = cache(async (): Promise<SiteContent> => {
headers: {
...(session ? { Cookie: `ccw_session=${encodeURIComponent(session)}` } : {}),
...(preview !== "admin" ? { "x-preview-token": preview } : {}),
...(jar.get("ccw_preview_template")?.value ? { "x-preview-template": jar.get("ccw_preview_template")!.value } : {}),
},
});
if (res.ok) return (await res.json()) as SiteContent;
+68 -9
View File
@@ -1,10 +1,13 @@
/**
* Search engine basics on every page (ROADMAP-v3 §11): a unique title and description, a
* canonical address, Open Graph with an image, and the church's JSON-LD on home and contact.
* Search engine basics on every page (ROADMAP-v3 §11, WEBSITE-1.0-PLAN §6): a unique title and
* description, a canonical address, Open Graph with an image (the page's own, else one made from
* the church's colours, logo and name: app/share-image), and schema.org JSON-LD: `Church` on home
* and contact, `Event` on the Website's own event pages, `VideoObject` / `PodcastEpisode` for
* messages, and `BreadcrumbList` on every page but home.
*/
import type { Metadata } from "next";
import { churchJsonLd, jsonLdString, pageMeta } from "@crosscode/seo";
import type { Page, Published } from "./types";
import type { Page, Published, SiteEvent, SiteMessage } from "./types";
export function siteBase(site: Published): URL | undefined {
try {
@@ -14,24 +17,80 @@ export function siteBase(site: Published): URL | undefined {
}
}
const abs = (site: Published, path: string) => {
const base = siteBase(site);
return base ? new URL(path, base).toString() : path;
};
/** The made share image for a title. */
export const shareImage = (title: string) => `/share-image?t=${encodeURIComponent(title.slice(0, 90))}`;
export function pageMetadata(site: Published, page: Page): Metadata {
const name = site.church?.name ?? "Church";
const meta = pageMeta({ title: page.kind === "home" ? null : page.seoTitle || page.title, description: page.description, fallbackDescription: `${name}: ${page.title}` });
const firstImage = page.image ?? Object.values(site.snapshot.media)[0] ?? null;
const image = firstImage?.url.endsWith(".svg") ? null : firstImage;
const own = page.image && !page.image.url.endsWith(".svg") ? page.image : null;
const title = page.kind === "home" ? name : page.title;
return {
metadataBase: siteBase(site),
title: page.kind === "home" ? { absolute: page.seoTitle || name } : meta.title,
description: meta.description,
alternates: { canonical: page.path },
openGraph: { type: "website", siteName: name, title: page.kind === "home" ? name : page.title, description: meta.description, url: page.path, locale: "en_ZA", ...(image ? { images: [{ url: image.url, alt: image.alt }] } : site.church?.branding.logoUrl ? { images: [site.church.branding.logoUrl] } : {}) },
twitter: { card: image ? "summary_large_image" : "summary" },
openGraph: {
type: "website", siteName: name, title, description: meta.description, url: page.path, locale: "en_ZA",
images: [own ? { url: own.url, alt: own.alt } : { url: shareImage(title), width: 1200, height: 630, alt: title }],
},
twitter: { card: "summary_large_image" },
};
}
/** `<script type="application/ld+json">` contents for the church (home and contact pages). */
export function churchLd(site: Published, path: string): string | null {
if (!site.church) return null;
const base = siteBase(site);
return jsonLdString(churchJsonLd(site.church, base ? { url: new URL(path, base).toString() } : {}));
return jsonLdString(churchJsonLd(site.church, siteBase(site) ? { url: abs(site, path) } : {}));
}
/** Home › … › this page. */
export function breadcrumbLd(site: Published, trail: { name: string; path: string }[]): string {
const items = [{ name: site.church?.name ?? "Home", path: "/" }, ...trail];
return jsonLdString({
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: items.map((x, i) => ({ "@type": "ListItem", position: i + 1, name: x.name, item: abs(site, x.path) })),
});
}
/** A simple event of the Website's own (events from Cross Events have theirs at the origin). */
export function eventLd(site: Published, e: SiteEvent): string {
const a = site.church?.contact.address;
const place = e.location || a
? { "@type": "Place", name: e.location ?? site.church?.name, ...(a ? { address: { "@type": "PostalAddress", streetAddress: [a.line1, a.line2].filter(Boolean).join(", "), addressLocality: a.city, postalCode: a.postalCode ?? undefined, addressCountry: a.country } } : {}) }
: undefined;
return jsonLdString({
"@context": "https://schema.org",
"@type": "Event",
name: e.title,
startDate: e.startsAt,
...(e.endsAt ? { endDate: e.endsAt } : {}),
eventStatus: "https://schema.org/EventScheduled",
eventAttendanceMode: "https://schema.org/OfflineEventAttendanceMode",
...(place ? { location: place } : {}),
...(e.summary ? { description: e.summary } : {}),
...(e.image ? { image: [abs(site, e.image.url)] } : {}),
url: abs(site, e.url),
organizer: { "@type": "Organization", name: site.church?.name, url: abs(site, "/") },
});
}
/** The messages on the Messages page: a VideoObject (YouTube) or PodcastEpisode (Spotify) each. */
export function messagesLd(site: Published, messages: SiteMessage[]): string | null {
if (!messages.length) return null;
return jsonLdString({
"@context": "https://schema.org",
"@graph": messages.slice(0, 20).map((m) => {
const description = [m.speaker, m.passage, m.series].filter(Boolean).join(" · ") || m.title;
return m.source === "spotify"
? { "@type": "PodcastEpisode", name: m.title, datePublished: m.date.slice(0, 10), description, url: m.url }
: { "@type": "VideoObject", name: m.title, uploadDate: m.date, description, ...(m.thumbnail ? { thumbnailUrl: [abs(site, m.thumbnail)] } : {}), ...(m.embedUrl ? { embedUrl: m.embedUrl.replace("?autoplay=1", "") } : {}), contentUrl: m.url };
}),
});
}
+15 -2
View File
@@ -3,13 +3,26 @@ import type { Image } from "./types";
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
/**
* An uploaded image at the size the screen needs (§3: responsive sizes in WebP and JPEG): the
* browser picks from the `srcset`s by `sizes`. `alt` overrides the image's own (e.g. "" when it's
* only decoration behind text).
*/
export function Picture({ image, className, sizes = "100vw", priority = false, alt }: { image: Image; className?: string; sizes?: string; priority?: boolean; alt?: string }) {
const img = (
<img src={image.url} srcSet={image.srcset?.jpg} sizes={image.srcset ? sizes : undefined} alt={alt ?? image.alt}
width={image.width ?? undefined} height={image.height ?? undefined}
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} />
);
return image.srcset ? <picture><source type="image/webp" srcSet={image.srcset.webp} sizes={sizes} />{img}</picture> : img;
}
/** An image in a frame (Heritage frames, duotone tints), or a soft placeholder when there's none. */
export function Img({ image, className, sizes = "(min-width: 768px) 50vw, 100vw", priority = false, ratio = "aspect-[4/3]" }: { image: Image | null; className?: string; sizes?: string; priority?: boolean; ratio?: string }) {
return (
<div className={cx("cc-frame", ratio, className)}>
{image ? (
<img src={image.url} alt={image.alt} sizes={sizes} width={image.width ?? undefined} height={image.height ?? undefined}
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className="cc-img" />
<Picture image={image} sizes={sizes} priority={priority} className="cc-img" />
) : (
<div aria-hidden="true" className="h-full w-full bg-gradient-to-br from-brand/25 via-brand-tint to-accent/30" />
)}
@@ -5,7 +5,7 @@
* photo.
*/
import { media } from "../load";
import { Button, cx, Img, type ButtonData } from "../parts";
import { Button, cx, Img, Picture, type ButtonData } from "../parts";
import type { Image, SectionProps } from "../types";
type HeroData = { headline: string; subline: string | null; images: string[]; videoId: string | null; button: ButtonData };
@@ -24,7 +24,7 @@ function Words({ d, centred, light, size = "cc-h1" }: { d: HeroData; centred?: b
function Video({ video, still, className }: { video: Image | null; still: Image | null; className?: string }) {
return (
<div className={cx("relative h-full w-full", className)}>
{still ? <img src={still.url} alt={still.alt} className="cc-img absolute inset-0" fetchPriority="high" /> : <div className="absolute inset-0 bg-brand" />}
{still ? <Picture image={still} priority className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand" />}
{video && (
<video className="cc-motion cc-img absolute inset-0 hidden sm:block" src={video.url} poster={still?.url} autoPlay muted loop playsInline aria-hidden="true" />
)}
@@ -79,7 +79,7 @@ export function Hero({ section, site, template }: SectionProps) {
if (template === "bold") {
return (
<section className="cc-section-hero grid bg-gray-950 text-white md:min-h-[80vh] md:grid-cols-2">
<div className="relative min-h-[50vh] md:order-2">{first && <img src={first.url} alt={first.alt} className="cc-img absolute inset-0" fetchPriority="high" />}</div>
<div className="relative min-h-[50vh] md:order-2">{first && <Picture image={first} sizes="(min-width: 768px) 50vw, 100vw" priority className="cc-img absolute inset-0" />}</div>
<div className="flex flex-col justify-center px-6 pb-16 pt-32 sm:px-12"><Words d={d} light /></div>
</section>
);
@@ -100,7 +100,7 @@ export function Hero({ section, site, template }: SectionProps) {
return (
<Fullbleed d={d} site={site}>
<div className="grid h-full grid-cols-3 gap-1">
{three.map((im, i) => <div key={i} className="relative">{im ? <img src={im.url} alt={im.alt} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
{three.map((im, i) => <div key={i} className="relative">{im ? <Picture image={im} sizes="34vw" priority={i === 0} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
</div>
</Fullbleed>
);
@@ -134,7 +134,7 @@ export function Hero({ section, site, template }: SectionProps) {
}
// photo (and video, drawn the same way with its loop).
const visual = variant === "video" ? <Video video={video} still={first} /> : first ? <img src={first.url} alt={first.alt} className="cc-img absolute inset-0" fetchPriority="high" /> : null;
const visual = variant === "video" ? <Video video={video} still={first} /> : first ? <Picture image={first} priority className="cc-img absolute inset-0" /> : null;
if (template === "bold") return <Fullbleed d={d} site={site}>{visual ?? <div className="h-full w-full bg-brand" />}</Fullbleed>;
if (template === "heritage") {
return (
@@ -2,9 +2,10 @@
* The homepage sections after the hero (WEBSITE-1.0-PLAN §3), each in its variants. Templates
* restyle the same markup through globals.css (cc-* classes) and the `t()` choices here.
*/
import { LazyMap } from "../LazyMap";
import { MessagePlayer } from "../MessagePlayer";
import { media, str, t } from "../load";
import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, SectionHeading, type ButtonData } from "../parts";
import { Button, cx, DateBadge, dayName, fmtDate, fmtTime, Img, Paragraphs, Picture, SectionHeading, type ButtonData } from "../parts";
import type { SectionProps, SiteEvent } from "../types";
import { Hero } from "./Hero";
@@ -62,7 +63,7 @@ function ServiceTimes(p: SectionProps) {
}
const panel = (
<div className={cx("p-8", t(p.template, { heritage: "border-4 border-double border-brand-text/40 text-center", bold: "bg-gray-950 text-white", community: "cc-card", clean: "border-l-4 border-accent" }))}>
<div className={cx("p-8", t(p.template, { heritage: "border-4 border-double border-brand-text/40 text-center", bold: "cc-dark bg-gray-950 text-white", community: "cc-card", clean: "border-l-4 border-accent" }))}>
<h2 className="cc-h2 mb-6">{heading}</h2>
<Times p={p} className={p.template === "heritage" ? "inline-block text-left" : ""} />
{d.note && <p className="cc-muted mt-6">{d.note}</p>}
@@ -82,11 +83,8 @@ function ServiceTimes(p: SectionProps) {
<div className="cc-wrap grid items-stretch gap-8 md:grid-cols-2">
{panel}
{geo ? (
<div className="cc-frame min-h-[18rem]">
{/* OpenStreetMap, loaded only when scrolled to (no Google, no cookies). */}
<iframe title="Map" loading="lazy" className="h-full min-h-[18rem] w-full border-0"
src={`https://www.openstreetmap.org/export/embed.html?bbox=${geo.lng - 0.006}%2C${geo.lat - 0.004}%2C${geo.lng + 0.006}%2C${geo.lat + 0.004}&layer=mapnik&marker=${geo.lat}%2C${geo.lng}`} />
</div>
<LazyMap href={dir}
src={`https://www.openstreetmap.org/export/embed.html?bbox=${geo.lng - 0.006}%2C${geo.lat - 0.004}%2C${geo.lng + 0.006}%2C${geo.lat + 0.004}&layer=mapnik&marker=${geo.lat}%2C${geo.lng}`} />
) : <Img image={null} ratio="min-h-[18rem]" />}
</div>
</Section>
@@ -302,8 +300,9 @@ function Events(p: SectionProps) {
<ol className="flex snap-x gap-4 overflow-x-auto pb-4">
{list.map((e) => (
<li key={e.url + e.startsAt} className="cc-card w-64 shrink-0 snap-start p-5">
<p className="font-heading text-4xl font-bold text-brand-text">{fmtDate(e.startsAt, zone, { day: "numeric" })}</p>
<p className="cc-eyebrow">{fmtDate(e.startsAt, zone, { month: "long", weekday: "short" })}</p>
<p className="font-heading text-4xl font-bold cc-brand-text">{fmtDate(e.startsAt, zone, { day: "numeric" })}</p>
{/* A weekday and month without a day is "Sun (month: November)" to Intl: two parts. */}
<p className="cc-eyebrow">{fmtDate(e.startsAt, zone, { weekday: "short" })} · {fmtDate(e.startsAt, zone, { month: "long" })}</p>
<h3 className="cc-h3 mt-3"><a href={e.url} className="no-underline hover:underline">{e.title}</a></h3>
{!e.allDay && <p className="cc-muted text-sm">{fmtTime(e.startsAt, zone)}</p>}
</li>
@@ -394,7 +393,7 @@ function Invitation(p: SectionProps) {
const img = media(p.site, d.imageId);
return (
<section className="cc-section cc-own-bg cc-dark relative isolate overflow-hidden bg-gray-900 text-white">
{img && <img src={img.url} alt="" className="cc-img absolute inset-0 -z-10" loading="lazy" />}
{img && <Picture image={img} alt="" className="cc-img absolute inset-0 -z-10" />}
<div className="absolute inset-0 -z-10 bg-black/60" aria-hidden="true" />
<div className="cc-wrap py-10 text-center">
<h2 className="cc-h2">{d.heading}</h2>
+8 -3
View File
@@ -6,7 +6,8 @@ import type { Church } from "@crosscode/contracts";
export type Template = "heritage" | "bold" | "community" | "clean";
export type Image = { url: string; alt: string; width: number | null; height: number | null };
/** An uploaded image; `srcset` lists its responsive sizes (WebP and JPEG) when it has them. */
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
export type Section = { type: string; variant: string | null; data: Record<string, unknown> };
@@ -37,6 +38,8 @@ export type Snapshot = {
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
media: Record<string, Image>;
/** Earlier page addresses and where each page is now (§6). */
redirects?: Record<string, string>;
};
export type Palette = { brand: string; brandDark: string; onBrand: string; brandText: string; brandTint: string; accent: string; onAccent: string; notes: string[] };
@@ -50,6 +53,8 @@ export type SiteEvent = {
location: string | null;
image: Image | null;
url: string;
slug: string | null;
link: string | null;
from: "website" | "events" | "app";
registration: { status: string; priceFromCents: number | null } | null;
};
@@ -67,7 +72,7 @@ export type SiteMessage = {
thumbnail: string | null;
};
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string } };
type Common = { church: Church | null; palette: Palette; style: { fontPairing: string; corners: string }; verification?: { google: string | null; bing: string | null } };
export type ComingSoon = Common & { mode: "coming-soon"; template: Template; comingSoonText: string };
@@ -79,7 +84,7 @@ export type Published = Common & {
messages: SiteMessage[];
events: SiteEvent[];
/** Only when previewing the working copy (§4). */
preview?: { by: "admin" | "link"; canPublish: boolean };
preview?: { by: "admin" | "link"; canPublish: boolean; template?: string | null };
};
export type SiteContent = ComingSoon | Published;
+4 -3
View File
@@ -2,7 +2,8 @@ import { defineConfig, devices } from "@playwright/test";
// The Website end to end (docs/WEBSITE-1.0-PLAN.md §13): the real backend on an in-memory database
// with the demo church (e2e/server.ts), and the Next.js pages (a production build). Run with `npx playwright test` in
// apps/website. Nothing needs a database.
// apps/website. Nothing needs a database; set E2E_DATABASE_URL (a database ending in _e2e, dropped and
// made again) to run the same suite on real Postgres. E2E_REUSE=1 uses servers already running on 5310 / 3310.
export default defineConfig({
testDir: "./e2e",
testMatch: "**/*.spec.ts",
@@ -19,7 +20,7 @@ export default defineConfig({
command: "npx tsx e2e/server.ts",
url: "http://127.0.0.1:5310/api/health",
timeout: 120_000,
reuseExistingServer: false,
reuseExistingServer: !!process.env.E2E_REUSE,
stdout: "pipe",
},
{
@@ -28,7 +29,7 @@ export default defineConfig({
cwd: "frontend",
url: "http://localhost:3310/robots.txt",
timeout: 300_000,
reuseExistingServer: false,
reuseExistingServer: !!process.env.E2E_REUSE,
env: { WEBSITE_API_URL: "http://127.0.0.1:5310", WEBSITE_CONTENT_CACHE_SECONDS: "0" },
},
],
+18 -4
View File
@@ -1,6 +1,6 @@
# Handover — Cross Code, all products
Last updated: 2026-11-25. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
Last updated: 2026-11-26. **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
@@ -34,7 +34,7 @@ every release).
| 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.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, 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 |
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (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). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26, not deployed yet. Left: deploy the site, Hope Family Church, a second church |
| 6–7 | App 1.0.0 → App 1.x | Not started |
## Released 2026-11-23
@@ -102,8 +102,22 @@ out").
[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; released 2026-11-24) → ~~Hub 2.21.0~~ (released
and deployed 2026-11-25; the plan said 2.13.0) → **`website@1.0.0`** (being built in `apps/website` since 2026-11-25: signing in, the four templates and public site, the admin with preview, publish and restore; next: roles, messages and events, image sizes, the event feed, Lighthouse, the VM test) → Hope Family Church → a second
church → crosscode-site 1.7.0.
and deployed 2026-11-25; the plan said 2.13.0) → ~~`website@1.0.0`~~ (released 2026-11-26, with
`contracts@1.18.0` and Hub `v2.22.0`, deployed 2026-11-26; the release checks are in
WEBSITE-1.0-PLAN §13, "Where they are"; the VM test was skipped, so watch the first install
closely) → ~~`website@1.0.1`~~ (released 2026-11-26: the messages' thumbnails served from the
site, the Calendar dates; VERSIONS.md) → **Hope Family Church**: roll out Accounts 1.7.0 and
Events 3.7.0 first (neither is rolled out yet), then New install → Website (1.0.1) → a second
church on a different template. ~~crosscode-site 1.7.0~~ (the Website on sale, released 2026-11-26;
the Hub already had its prices): **deploy it** (`deploy/deploy.sh` on the server) once Hope
Family Church's Website is live, so the first church to buy it isn't the first install.
The release checks are all run on 1.0.1's build (WEBSITE-1.0-PLAN §13, "Where they are"): every
variant passes axe, the 312 screenshots have baselines (taken again with whole-pixel section
heights), Lighthouse passes 12 of 12. Still to do:
- **Look through the variant baselines** once (the contact sheet: Bold, Community and Clean were
taken, not compared, the first time). A section drawn wrong there is the reference until then.
- **The VM test was skipped**: before Hope Family Church, a throwaway install from the Hub (New
install → Website 1.0.0, update it to 1.0.1, uninstall with its export) in its place.
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/`.
+64 -9
View File
@@ -1,6 +1,6 @@
# Versions — the latest release of everything
Last updated: 2026-11-24. Taken from the git tags, which is what a release is here (branch → merge →
Last updated: 2026-11-26. Taken from the git tags, which is what a release is here (branch → merge →
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
@@ -10,12 +10,13 @@ separately below; the two often differ.
| What | Repo | Latest | Tag | Released |
|------|------|--------|-----|----------|
| 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 |
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.1** | `events@3.7.1` | 2026-11-26 |
| Church Website | `crosscode-platform` (`apps/website`) | **1.0.2** | `website@1.0.2` | 2026-11-26 |
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.7.1** | `accounts@1.7.1` | 2026-11-26 |
| 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.21.0** | `v2.21.0` | 2026-11-25 |
| crosscode.co.za | `crosscode-site` | **1.6.1** | `v1.6.1` | 2026-11-23 |
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.18.0** | `contracts@1.18.0` | 2026-11-25 |
| Cross Code Hub | `events-hub` | **2.23.1** | `v2.23.1` | 2026-11-26 |
| crosscode.co.za | `crosscode-site` | **1.7.0** | `v1.7.0` | 2026-11-26 |
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-23 (last change: uninstall, export and purge one product of a church) |
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
@@ -29,7 +30,7 @@ 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.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) |
| Website | `apps/website` | 1.0.2 (1.0.0–1.0.2 released 2026-11-26; installed for the demo church cross-demo2 (1.0.1) only, Hope Family Church next) |
| 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,12 +38,59 @@ need their own tags until something outside this repo depends on them.
## What each latest release was for
- **Accounts 1.7.1 + Church Website 1.0.2 + Cross Events 3.7.1 (2026-11-26):** found installing
the Website for cross-demo2. All three: a connect involving an install that isn't in the cached
copy of the Hub's list yet asks the Hub for a fresh one (one heartbeat, at most once a minute)
instead of refusing, so a new product links straight away. Before, the new Website's admin
couldn't sign in for up to 30 minutes ("can't reach your church's sign-in"). Accounts also sends a
heartbeat on every start. The Website links on the spot when someone opens `/admin`, its problem
page says "not linked yet" (`ACCOUNTS_NOT_LINKED`), and **Preview no longer redirects to the
server's own `http://localhost:<web port>`** (the preview routes built absolute URLs from
`request.url`; now relative). No migrations. Checked: the backend tests (Accounts 80, Website 100,
Events 801), typechecks, the Website's frontend lint and build, the preview redirects against
`next start`, and the Website's e2e suite. **Not deployed yet.**
- **Hub 2.23.1 (2026-11-26):** New install reads a church's Accounts version from its heartbeat,
not the install record. The record only changed with the Hub's own jobs for that product, so
cross-demo2's Accounts, updated alongside Events 3.7.0, still showed 1.6.0 there. New install →
Website was refused ("this church has 1.6.0") while the installs list showed 1.7.0. Each heartbeat
now also updates the record's version. No migration. **Deployed 2026-11-26.**
- **Hub 2.23.0 (2026-11-26):** release requirements carry forward. A release needs what every
earlier release of its product needed (the highest version per product; a later heading can raise
it, never lower or drop it), so `— requires accounts 1.7.0` is written once in WHATS-NEW.md, on
the release that first needs it. Found when New install → Website 1.0.1 sent a Website-only
`install` job, which agent 1.5.0 refused ("installs one product at a time: Events or Accounts"):
1.0.1's heading didn't repeat 1.0.0's requirement, so Accounts wasn't installed first. No
migration; the next release sync fixes the stored requirements. **Deployed 2026-11-26.**
- **Church Website 1.0.1 (2026-11-26):** the messages' YouTube thumbnails are served from the site
(`/api/thumbnails/<id>.jpg`, fetched once by the backend and kept in `uploads/.thumbnails/`), so a
visitor asks nothing of YouTube until pressing play (plan §7); the Calendar events' dates read
"Sun · November", not "Sun (month: November)". No migration. Checked: the backend tests (97),
the whole e2e suite on the release build (Lighthouse 12 of 12, performance 90–100: Heritage's
messages from 89 to 95), the 312 variant screenshots (taken again with whole-pixel section heights,
which ended a one-pixel flake), and an e2e check that the messages page makes no request to
YouTube or Spotify before a click. The `crosscode` script's Website export leaves out
`uploads/.thumbnails`. **Not installed for a church yet.**
- **Church Website 1.0.0 (2026-11-26):** the first release (WEBSITE-1.0-PLAN): four templates with
section variants and style settings, drafts, preview and one Publish, people and roles, messages
from YouTube, simple events and the event feed, church details through Accounts, SEO, Get more
storage. Requires Accounts 1.7.0. Checked before tagging: the backend tests, the e2e suite (every
template, the admin flows, Lighthouse on a phone; axe on every section variant ran in full on an
earlier build and on 36 of 104 on the final one), the admin flows
and pages on real Postgres (20/20), a backup restored (every table the same) and the uninstall
export on Postgres, the migrations against the schema. The VM test was skipped (no VM on
this machine; the install path was read through instead). **Not installed for a church yet.**
- **Contracts 1.18.0 + Hub 2.22.0 (2026-11-25):** "Get more storage" for the Church Website (WEBSITE-1.0-PLAN
§10, decision 12). Contracts: `hub.storageRequestSchema` and its reply. Hub: `POST
/api/installs/storage-request` (shown on the install, Joshua emailed once, closed when the licence
gets more extra storage steps), and the church emailed once at 80% and once when full, from the
Website's heartbeat. The Hub vendors contracts 1.18.0. No migration. **Deployed 2026-11-26.**
- **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.**
with the Website (contracts 1.18.0, Hub 2.22.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
@@ -95,6 +143,13 @@ need their own tags until something outside this repo depends on them.
release in a ⋯ menu); contact and billing details are one form; the history is one timeline with
a filter. Record payment is a popup on Billing too. Frontend only: no migration, no API changes.
Deployed 2026-11-23.
- **crosscode.co.za 1.7.0 (2026-11-26):** the Church Website on sale (ROADMAP §9, phase 5): its own
page (`/products/church-website/`: features, the four templates with the same fictional demo church
in each, the section layouts, R99 a month, founding R64, extra storage R20 per 5 GB, the 15% bundle
with Cross Events, FAQ, `SoftwareApplication` JSON-LD with its offer) and a page per template; the
products and home pages, the contact form's topics, the Cross Events page and the brochure updated.
Screenshots from the Website's e2e demo (`npm run screenshots:website`). The Hub already had these
prices (2.21.0). **Not deployed yet** (`deploy/deploy.sh` on the server).
- **crosscode.co.za 1.6.1 (2026-11-23):** the web address choices on the Cross Events page are three
cards (name, price, "best if", an example address, short points); the option names were white on
a light background and couldn't be seen. Prices unchanged. Deployed 2026-11-23.
@@ -223,7 +278,7 @@ you deploy one.
| What | Running | Since | Notes |
|------|---------|-------|-------|
| 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 |
| Hub | 2.23.1 | 2026-11-26 | A church's Accounts version comes from its heartbeat in New install, and heartbeats keep the install record's version current. Before it, 2.23.0 (2026-11-26): release requirements carry forward (`requires accounts …` written once in WHATS-NEW.md) |
| 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 |
+37
View File
@@ -529,6 +529,31 @@ only freed when neither the working copy nor the last 10 published versions use
- **The release checks** (ROADMAP §9) for the Website, and the **VM test**: install the Website
next to Accounts and Events through the agent, update it, uninstall it with its export.
**Where they are (2026-11-26):** `apps/website/e2e/`: `templates.spec.ts` and `admin.spec.ts` (the
pages and flows), `variants.spec.ts` (every variant: axe and the 312 screenshots, compared with
baselines kept on the machine that runs them, not in git), `lighthouse.spec.ts` (mobile, the median
of three runs with the CPU slowdown calibrated to the machine). `E2E_DATABASE_URL=…_e2e` runs the
whole suite on real Postgres.
**Run again on the release build (2026-11-26):** `npx playwright test variants lighthouse`, 19.6 minutes.
Every variant in every template passes axe. The screenshot baselines are complete: the 37 that existed
(Heritage, and Bold up to Ministries) matched, and the other 67 variants' 201 screenshots were taken
(they still need a look through). Lighthouse (mobile): SEO and accessibility 100 on every page;
performance 92–99 except Heritage's messages, 89 (LCP 3.0 s: the first message's YouTube thumbnail,
from `i.ytimg.com`). Community's home, 84 in the run before, was 97: the machine's benchmark moved
between 1169 and 2542 in one run, so a score within a few points of 90 is worth a second run before
it counts as a regression. Found in the screenshots: the Calendar events variant prints the date as
"Sun (month: November)" (for `website@1.0.1`).
**On 1.0.1 (2026-11-26):** the whole suite, `npx playwright test` (129 tests, 34.6 minutes): the admin
flows, every template's pages, Lighthouse 12 of 12 (performance 90–100; Heritage's messages 95, the
thumbnail now from the site), and a new check that the messages page asks nothing of YouTube or
Spotify before play. Seven variant screenshots failed by a pixel of height in that run and passed
when run again: a section starting at a fractional position came out 534 or 535 pixels tall.
`variants.spec.ts` now rounds the header's and each section's height up before the screenshot
(`wholePixels`), and the 312 baselines were taken again with it (113 came out the same), then
compared in a second full run of the variants.
## 14. Releasing and rolling it out
1. `contracts@1.17.0`, then `accounts@1.7.0` (the profile's brand style), then `events@3.7.0`.
@@ -589,6 +614,18 @@ Confirmed on 2026-11-25:
17. **The first Owner** (§10): whoever signs in through Accounts with the Hub's admin email
(`HUB_ADMIN_EMAIL`), verified in Accounts, while the site has no Owner.
## Moved to website@1.1.0
Decided by Joshua on 2026-11-25, to ship 1.0 sooner:
- **The Video hero with its own loop** (§3): 1.0 uploads photos only, so the Video layout shows its
still.
- **The other custom-page blocks** (§3, "Pages from blocks"): gallery, video, FAQ, map, people cards
and divider. 1.0 has text, image and text, quote and call to action.
- **More pages** (§6, §7, §8): a page per ministry (1.0: one Ministries page with a section each),
the events calendar and past events, message detail and series pages, and starter Terms and
Safeguarding pages.
## Still open
- Whether the App (phase 6) moves leaders, ministries and giving into `crosscode.church/1` or reads

Some files were not shown because too many files have changed in this diff Show More