Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84c5b0c08e | ||
|
|
3caa1d1e1a | ||
|
|
5ed7201efa | ||
|
|
138c73e20c | ||
|
|
58960b5e93 | ||
|
|
79121bc447 | ||
|
|
36ceb358b8 | ||
|
|
a3a158faa8 | ||
|
|
ae604268e0 | ||
|
|
ae122a664a | ||
|
|
62d9728b95 | ||
|
|
ee129fbd87 |
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -0,0 +1,64 @@
|
||||
# Changelog — Church Website
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- The app's skeleton (WEBSITE-1.0-PLAN §1): an Express + Prisma backend with `/api/health` and
|
||||
`/api/v1/site/status` (Coming soon until the first publish), the content model and its first
|
||||
migration, the section variants per template (§3, decision 16) with the template switch rules, and
|
||||
a Next.js frontend with the Coming soon page, an admin placeholder and `robots.txt`.
|
||||
- **Signing in to the admin through the church's Accounts** (§10), as Cross Events 3.x: the Hub
|
||||
client (protocol v2, product `website`, registers from `HUB_LICENCE_KEY`, heartbeats with
|
||||
aggregate counts), links (`crosscode.link/1`; the Website connects itself to the church's Accounts
|
||||
once the Hub lists it), `/api/auth/signin`, `/callback`, `/me`, `/signout` (then Accounts'
|
||||
sign-out), back-channel logout and Accounts' calls (`user.updated`, `user.export`,
|
||||
`user.deleted`). The Website keeps its own session (`ccw_session`, only a hash stored) and its own
|
||||
roles; the **first Owner** is whoever signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`,
|
||||
verified in Accounts) while the site has none. Owners and Admins sign in with a second step
|
||||
(`two_factor_required_for_admins`, on by default); asked of Accounts once, then explained.
|
||||
- **The four templates and the public site** (§3, §5, §6): Heritage, Bold, Community and Clean,
|
||||
each drawing all 26 section variants its own way, with its headers, homepage order and style
|
||||
settings (section colour, spacing, buttons, image treatment). The church's colours are made safe
|
||||
by the backend (`site/palette.ts`: tints, shades and text colours checked against WCAG AA, with a
|
||||
note for the admin when one is changed); fonts and corners come from its shared brand style, else
|
||||
the template's suggestion. Pages: home, every page kind (visit, about, ministries, leadership,
|
||||
events, messages, give, contact, custom) with its blocks, simple event pages, a real 404,
|
||||
Coming soon from the church profile, `sitemap.xml` and `robots.txt`. Every page has a title,
|
||||
description, canonical, Open Graph and one `<h1>`; home and contact have the church's JSON-LD.
|
||||
Messages load YouTube (youtube-nocookie) or Spotify only when clicked; maps are OpenStreetMap.
|
||||
- **Publishing** (`site/snapshot.ts`): Publish copies the working copy into a numbered version;
|
||||
visitors see the latest (`GET /api/v1/site/content`, with live messages and events and the church
|
||||
profile from Accounts, kept 10 minutes). Section data is checked per type (`site/sections.ts`); a
|
||||
section that doesn't fit is left out, never shown broken. Uploads are served from
|
||||
`/api/uploads/` (SVGs sandboxed).
|
||||
- **The demo church** (`npm run demo -- --template <id>`): Acacia Hill Church, fictional, with
|
||||
illustrated images; refuses to replace a site its admins published unless `--force`.
|
||||
- **End to end** (`npx playwright test` in apps/website, no database, a production build): every
|
||||
template's pages pass axe (WCAG 2.2 AA) and the SEO basics, with screenshots at phone and desktop in
|
||||
`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 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
|
||||
engine title and description with a search result preview, the home page's sections, other pages'
|
||||
blocks: add, move, hide, remove; custom pages); Ministries and Leadership; the media library
|
||||
(uploads checked by their bytes, alt text, storage; **uploads stop when storage is full**); and
|
||||
Publish and history. Roles: a Viewer reads, an Editor and above changes and publishes, a Ministry
|
||||
leader edits only their own ministry. Every change comes from the site itself (same origin).
|
||||
- **Drafts, preview and publish** (§4): every change is a draft; the pending list says what changed,
|
||||
who and when, and any one can be **discarded**; one **Publish** for the whole site, with a note;
|
||||
every version is kept and any can be **restored** into the working copy (each version keeps the
|
||||
working copy's rows, never sent to visitors). The **preview** shows the working copy on the site's
|
||||
own addresses, fully clickable, with a bar above the page (phone / tablet / desktop width, Back to
|
||||
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).
|
||||
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
|
||||
- **The church's export** (`scripts/export-church.ts`): `export.json` in
|
||||
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
|
||||
- **`crosscode`:** `scripts/products/website.sh` (the same hooks as Accounts, ports 5300 / 3300,
|
||||
uploads in the export), `crosscode add <church> website` (needs the church's Accounts; served on
|
||||
`www.<address>`, or the Cross Code address itself), and the installer shared by Accounts and the
|
||||
Website (`install_app`).
|
||||
+28
-1
@@ -1,3 +1,30 @@
|
||||
# Church Website
|
||||
|
||||
Placeholder: the church's public website and its admin. Built in phase 5 of ROADMAP-v3 (see §6 there).
|
||||
The church's public website and its admin (ROADMAP-v3 §6, phase 5; plan and decisions in
|
||||
[docs/WEBSITE-1.0-PLAN.md](../../docs/WEBSITE-1.0-PLAN.md)). Served at `www.<church's address>` (or
|
||||
`<church>.crosscode.co.za`), with the admin at `/admin`, signed in through the church's Accounts.
|
||||
The church picks one of four templates (Heritage, Bold, Community, Clean) and makes it its own with
|
||||
section variants and style settings. Changes are drafts until an editor previews the whole site and
|
||||
presses Publish; until the first publish visitors see Coming soon.
|
||||
|
||||
**State:** being built (2026-11-25): 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;
|
||||
`website@1.0.0` is tagged when the plan is built.
|
||||
|
||||
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
|
||||
client id at Accounts), links itself to the church's Accounts once the Hub lists it, and signs
|
||||
admins in through `@crosscode/auth-client`. Roles are the Website's own; the first Owner is whoever
|
||||
signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`), verified in Accounts. Locally, set
|
||||
`LINKS_ALLOW_PRIVATE=true` to link to an Accounts on http://localhost.
|
||||
|
||||
- `backend/`: Express + Prisma (ES modules), as Accounts. `npm run dev`, `npm test` (Node's test
|
||||
runner through tsx), `npm run build`. The content model is in `prisma/schema.prisma`; the section
|
||||
variants per template (plan §3, decision 16) in `src/site/variants.ts`.
|
||||
- `frontend/`: Next.js 16. The public site (server-rendered from the latest published version) and
|
||||
the admin.
|
||||
|
||||
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `WEBSITE_URL=http://localhost:3300`),
|
||||
`npx prisma migrate deploy`, then `npm run dev` in both folders (the frontend runs on 3300 and sends
|
||||
/api to the backend on 5300).
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# What's new in the Church Website
|
||||
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
src/generated/
|
||||
.env
|
||||
uploads/
|
||||
exports/
|
||||
/backups/
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status",
|
||||
"demo": "tsx scripts/demo.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"prisma": "^7.10.1",
|
||||
"supertest": "^7.3.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
|
||||
import 'dotenv/config';
|
||||
import { defineConfig } from 'prisma/config';
|
||||
|
||||
export default defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: { path: 'prisma/migrations' },
|
||||
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
|
||||
datasource: { url: process.env.DATABASE_URL ?? '' },
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §10).
|
||||
|
||||
-- CreateSchema
|
||||
CREATE SCHEMA IF NOT EXISTS "public";
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WebsiteRole" AS ENUM ('owner', 'admin', 'editor', 'ministry_leader', 'viewer');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PageKind" AS ENUM ('home', 'visit', 'about', 'leadership', 'ministries', 'events', 'messages', 'give', 'contact', 'terms', 'safeguarding', 'custom');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MessageSource" AS ENUM ('youtube_feed', 'youtube', 'spotify');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SiteDesign" (
|
||||
"id" INTEGER NOT NULL DEFAULT 1,
|
||||
"template" TEXT NOT NULL,
|
||||
"variants" JSONB NOT NULL,
|
||||
"home" JSONB NOT NULL,
|
||||
"style" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "SiteDesign_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Page" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kind" "PageKind" NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"seoTitle" TEXT,
|
||||
"description" TEXT,
|
||||
"navLabel" TEXT,
|
||||
"inNav" BOOLEAN NOT NULL DEFAULT true,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"imageId" TEXT,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Page_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Section" (
|
||||
"id" TEXT NOT NULL,
|
||||
"pageId" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"variant" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"data" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Ministry" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"summary" TEXT,
|
||||
"body" TEXT,
|
||||
"imageId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Leader" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT,
|
||||
"bio" TEXT,
|
||||
"photoId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Leader_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MessageSeries" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"summary" TEXT,
|
||||
"imageId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MessageSeries_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Message" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"date" TIMESTAMP(3) NOT NULL,
|
||||
"source" "MessageSource" NOT NULL,
|
||||
"mediaUrl" TEXT NOT NULL,
|
||||
"externalId" TEXT,
|
||||
"thumbnailUrl" TEXT,
|
||||
"speaker" TEXT,
|
||||
"passage" TEXT,
|
||||
"notes" TEXT,
|
||||
"seriesId" TEXT,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SimpleEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"endsAt" TIMESTAMP(3),
|
||||
"allDay" BOOLEAN NOT NULL DEFAULT false,
|
||||
"timezone" TEXT NOT NULL DEFAULT 'Africa/Johannesburg',
|
||||
"location" TEXT,
|
||||
"description" TEXT,
|
||||
"imageId" TEXT,
|
||||
"link" TEXT,
|
||||
"cancelled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "SimpleEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ImportedEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"originProduct" TEXT NOT NULL,
|
||||
"originId" TEXT NOT NULL,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"data" JSONB NOT NULL,
|
||||
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MediaAsset" (
|
||||
"id" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
"mime" TEXT NOT NULL,
|
||||
"bytes" INTEGER NOT NULL,
|
||||
"width" INTEGER,
|
||||
"height" INTEGER,
|
||||
"alt" TEXT NOT NULL DEFAULT '',
|
||||
"sizes" JSONB,
|
||||
"uploadedBy" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SiteVersion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"number" INTEGER NOT NULL,
|
||||
"snapshot" JSONB NOT NULL,
|
||||
"note" TEXT,
|
||||
"publishedBy" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PreviewLink" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "PreviewLink_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "WebsiteUser" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" "WebsiteRole" NOT NULL,
|
||||
"ministryId" TEXT,
|
||||
"lastSignInAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "WebsiteUser_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"sid" TEXT,
|
||||
"mfa" BOOLEAN NOT NULL DEFAULT false,
|
||||
"idToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProductLink" (
|
||||
"installId" TEXT NOT NULL,
|
||||
"product" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"publicKey" TEXT NOT NULL,
|
||||
"secret" TEXT NOT NULL,
|
||||
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"connectedById" TEXT,
|
||||
"lastSyncError" TEXT,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "LinkNonce" (
|
||||
"nonce" TEXT NOT NULL,
|
||||
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorRole" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"targetType" TEXT NOT NULL,
|
||||
"targetId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AppSetting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Page_slug_key" ON "Page"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Page_kind_idx" ON "Page"("kind");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Section_pageId_position_idx" ON "Section"("pageId", "position");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MessageSeries_slug_key" ON "MessageSeries"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Message_slug_key" ON "Message"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Message_externalId_key" ON "Message"("externalId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Message_date_idx" ON "Message"("date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SimpleEvent_slug_key" ON "SimpleEvent"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SiteVersion_number_key" ON "SiteVersion"("number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PreviewLink_tokenHash_key" ON "PreviewLink"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_tokenHash_key" ON "Session"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_sid_idx" ON "Session"("sid");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Message" ADD CONSTRAINT "Message_seriesId_fkey" FOREIGN KEY ("seriesId") REFERENCES "MessageSeries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WebsiteUser" ADD CONSTRAINT "WebsiteUser_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,301 @@
|
||||
// Church Website 1.0.0 (docs/WEBSITE-1.0-PLAN.md). One database per church.
|
||||
//
|
||||
// The content tables are the **working copy** the admin edits (§4). Publishing writes an immutable
|
||||
// snapshot of them to SiteVersion; visitors always see the latest SiteVersion, the preview sees the
|
||||
// working copy. Shared facts (name, logo, colours, service times, contact, the brand style) are the
|
||||
// church profile's, in Accounts (§2), and are never stored here.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
|
||||
output = "../src/generated/prisma"
|
||||
moduleFormat = "esm"
|
||||
importFileExtension = "js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
/// Website roles (§10). Held here, per product: an Events role gives nothing in the Website.
|
||||
enum WebsiteRole {
|
||||
owner
|
||||
admin
|
||||
editor
|
||||
ministry_leader
|
||||
viewer
|
||||
}
|
||||
|
||||
enum PageKind {
|
||||
home
|
||||
visit
|
||||
about
|
||||
leadership
|
||||
ministries
|
||||
events
|
||||
messages
|
||||
give
|
||||
contact
|
||||
terms
|
||||
safeguarding
|
||||
custom
|
||||
}
|
||||
|
||||
enum MessageSource {
|
||||
youtube_feed
|
||||
youtube
|
||||
spotify
|
||||
}
|
||||
|
||||
/// The site's design in the working copy (one row, id 1): template, section variants, homepage
|
||||
/// order and the Website-only style settings (src/site/variants.ts). Fonts and corners are shared.
|
||||
model SiteDesign {
|
||||
id Int @id @default(1)
|
||||
template String
|
||||
variants Json
|
||||
home Json
|
||||
style Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
}
|
||||
|
||||
/// A page: the fixed ones (§6) and custom pages built from blocks.
|
||||
model Page {
|
||||
id String @id @default(uuid())
|
||||
kind PageKind
|
||||
slug String @unique
|
||||
title String
|
||||
/// Per-page SEO (ROADMAP-v3 §11); null uses the generated one.
|
||||
seoTitle String?
|
||||
description String?
|
||||
navLabel String?
|
||||
inNav Boolean @default(true)
|
||||
position Int @default(0)
|
||||
imageId String?
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
sections Section[]
|
||||
|
||||
@@index([kind])
|
||||
}
|
||||
|
||||
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
|
||||
/// is one of that type's ids. Content is never tied to a template (§2).
|
||||
model Section {
|
||||
id String @id @default(uuid())
|
||||
pageId String
|
||||
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
|
||||
type String
|
||||
variant String?
|
||||
position Int @default(0)
|
||||
hidden Boolean @default(false)
|
||||
data Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([pageId, position])
|
||||
}
|
||||
|
||||
model Ministry {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
name String
|
||||
summary String?
|
||||
body String?
|
||||
imageId String?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
leaders WebsiteUser[]
|
||||
}
|
||||
|
||||
model Leader {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
role String?
|
||||
bio String?
|
||||
photoId String?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
}
|
||||
|
||||
model MessageSeries {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
summary String?
|
||||
imageId String?
|
||||
createdAt DateTime @default(now())
|
||||
messages Message[]
|
||||
}
|
||||
|
||||
/// A message (sermon), from the YouTube feed or added by hand (§7). Published on its own, not with
|
||||
/// the site's Publish (decision 9). Audio and video are linked, never uploaded.
|
||||
model Message {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
date DateTime
|
||||
source MessageSource
|
||||
mediaUrl String
|
||||
/// The YouTube video id or Spotify episode id: one message per video, whichever way it came in.
|
||||
externalId String? @unique
|
||||
thumbnailUrl String?
|
||||
speaker String?
|
||||
passage String?
|
||||
notes String?
|
||||
seriesId String?
|
||||
series MessageSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
|
||||
hidden Boolean @default(false)
|
||||
publishedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([date])
|
||||
}
|
||||
|
||||
/// A simple event made in the Website (§8). Registrations and payments are only Cross Events'.
|
||||
model SimpleEvent {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
startsAt DateTime
|
||||
endsAt DateTime?
|
||||
allDay Boolean @default(false)
|
||||
timezone String @default("Africa/Johannesburg")
|
||||
location String?
|
||||
description String?
|
||||
imageId String?
|
||||
link String?
|
||||
cancelled Boolean @default(false)
|
||||
publishedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([startsAt])
|
||||
}
|
||||
|
||||
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4).
|
||||
model ImportedEvent {
|
||||
id String @id @default(uuid())
|
||||
originProduct String
|
||||
originId String
|
||||
startsAt DateTime
|
||||
data Json
|
||||
syncedAt DateTime @default(now())
|
||||
|
||||
@@unique([originProduct, originId])
|
||||
@@index([startsAt])
|
||||
}
|
||||
|
||||
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
|
||||
/// published versions use it.
|
||||
model MediaAsset {
|
||||
id String @id @default(uuid())
|
||||
filename String
|
||||
mime String
|
||||
bytes Int
|
||||
width Int?
|
||||
height Int?
|
||||
alt String @default("")
|
||||
/// The resized files (WebP and JPEG per width) and their sizes, counted with `bytes`.
|
||||
sizes Json?
|
||||
uploadedBy String?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A published version: an immutable snapshot of the working copy (§4). Restore copies one back.
|
||||
model SiteVersion {
|
||||
id String @id @default(uuid())
|
||||
number Int @unique
|
||||
snapshot Json
|
||||
note String?
|
||||
publishedBy String
|
||||
publishedAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked.
|
||||
model PreviewLink {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
createdBy String
|
||||
createdAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
revokedAt DateTime?
|
||||
}
|
||||
|
||||
/// Someone who can use the admin: keyed by their account's `sub` from Accounts.
|
||||
model WebsiteUser {
|
||||
id String @id
|
||||
email String
|
||||
name String
|
||||
role WebsiteRole
|
||||
/// A Ministry leader edits only their own ministry.
|
||||
ministryId String?
|
||||
ministry Ministry? @relation(fields: [ministryId], references: [id], onDelete: SetNull)
|
||||
lastSignInAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A signed-in admin session (the `ccw_session` cookie holds the token; only its SHA-256 is kept).
|
||||
/// `sid` is Accounts' session id, so a back-channel logout ends the matching sessions.
|
||||
model Session {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
userId String
|
||||
sid String?
|
||||
/// Whether Accounts did a second step for this sign-in (`amr` has `mfa`).
|
||||
mfa Boolean @default(false)
|
||||
/// The ID token (encrypted), for "Sign out" at Accounts (`id_token_hint`).
|
||||
idToken String?
|
||||
createdAt DateTime @default(now())
|
||||
lastSeenAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
|
||||
@@index([userId])
|
||||
@@index([sid])
|
||||
}
|
||||
|
||||
/// A link to another of the church's products (`crosscode.link/1`, as Events 2.4): Accounts, for
|
||||
/// signing in, and Events / the App for the event feed. The secret is encrypted.
|
||||
model ProductLink {
|
||||
installId String @id
|
||||
product String
|
||||
url String
|
||||
publicKey String
|
||||
secret String
|
||||
connectedAt DateTime @default(now())
|
||||
connectedById String?
|
||||
lastSyncError String?
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
/// Nonces of link messages seen in the last hour (replays are refused).
|
||||
model LinkNonce {
|
||||
nonce String @id
|
||||
seenAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
actorId String?
|
||||
actorRole String
|
||||
action String
|
||||
targetType String
|
||||
targetId String?
|
||||
metadata Json?
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model AppSetting {
|
||||
key String @id
|
||||
value String
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
|
||||
*
|
||||
* npm run demo -- --template heritage|bold|community|clean [--force]
|
||||
*
|
||||
* It replaces the site's content, so a site that has been published needs --force.
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
|
||||
const arg = (name: string) => {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > 0 ? process.argv[i + 1] : undefined;
|
||||
};
|
||||
const template = websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
|
||||
if (!template.success) {
|
||||
console.error('Usage: npm run demo -- --template heritage|bold|community|clean [--force]');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const ctx = createCtx(loadConfig(), db);
|
||||
const published = await db.siteVersion.findFirst({ where: { NOT: { publishedBy: 'demo' } } });
|
||||
if (published && !process.argv.includes('--force')) {
|
||||
console.error('This site has been published by its admins: loading the demo would replace their content. Add --force to do it anyway.');
|
||||
await db.$disconnect();
|
||||
process.exit(1);
|
||||
}
|
||||
const version = await loadDemo(ctx, template.data);
|
||||
console.log(`Demo church loaded on ${template.data} and published (version ${version.number}).`);
|
||||
await db.$disconnect();
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* The Website's part of a church's export (`crosscode export` / uninstall): `export.json` in
|
||||
* --out-dir (src/export/churchExport.ts). The crosscode script adds the uploads next to it.
|
||||
*
|
||||
* npx tsx scripts/export-church.ts --out-dir <dir>
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { buildExport } from '../src/export/churchExport.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
|
||||
const i = process.argv.indexOf('--out-dir');
|
||||
const out = i > 0 ? process.argv[i + 1] : null;
|
||||
if (!out) {
|
||||
console.error('Usage: export-church.ts --out-dir <dir>');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const data = await buildExport(createCtx(loadConfig(), db));
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
fs.writeFileSync(path.join(out, 'export.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
|
||||
console.log(` export.json: ${data.website!.pages.length} pages, ${data.website!.messages.length} messages, ${data.files.length} files`);
|
||||
await db.$disconnect();
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Editing the working copy (WEBSITE-1.0-PLAN §4, §10): the site's design (template, section
|
||||
* variants, homepage order, style), pages and their sections or blocks, ministries and leaders.
|
||||
* Every change is a draft until Publish; each row records who changed it last (`updatedBy`).
|
||||
*
|
||||
* Shared facts (name, logo, colours, service times, contact) aren't here: they're the church
|
||||
* profile's, saved through Accounts (§2), and go live at once.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { BLOCK_SCHEMAS, isBlockType, SECTION_SCHEMAS } from '../site/sections.js';
|
||||
import { cleanDesign } from '../site/snapshot.js';
|
||||
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
/** zod issues as `{ field: message }`, for the form. */
|
||||
function fieldsOf(e: z.ZodError): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const i of e.issues) out[i.path.join('.') || '_'] ??= i.message;
|
||||
return out;
|
||||
}
|
||||
|
||||
function check<T>(schema: z.ZodType<T>, body: unknown): T {
|
||||
const r = schema.safeParse(body);
|
||||
if (!r.success) throw new ApiError(400, 'VALIDATION', 'Some fields need another look.', fieldsOf(r.error));
|
||||
return r.data;
|
||||
}
|
||||
|
||||
// ─── Design ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getDesign(ctx: Ctx) {
|
||||
return cleanDesign(await ctx.db.siteDesign.findUnique({ where: { id: 1 } }));
|
||||
}
|
||||
|
||||
const designPatch = z.object({
|
||||
template: websiteTemplateSchema.optional(),
|
||||
variants: z.record(z.string(), z.string()).optional(),
|
||||
home: z.array(z.object({ section: sectionTypeSchema, hidden: z.boolean() })).max(SECTION_TYPES.length).optional(),
|
||||
style: z.object({
|
||||
sectionColour: z.enum(SECTION_COLOURS).optional(),
|
||||
spacing: z.enum(SPACINGS).optional(),
|
||||
buttons: z.enum(BUTTONS).optional(),
|
||||
images: z.enum(IMAGE_TREATMENTS).optional(),
|
||||
header: z.string().max(40).optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Changes the design. A template switch first moves everything still on the old template's
|
||||
* defaults to the new one's and keeps the church's own choices (§3); the rest of the patch then
|
||||
* applies. Returns what the switch moved, for the screen.
|
||||
*/
|
||||
export async function saveDesign(ctx: Ctx, body: unknown, by: Who) {
|
||||
const patch = check(designPatch, body);
|
||||
let design = await getDesign(ctx);
|
||||
let moved: { what: string; from: string; to: string }[] = [];
|
||||
if (patch.template && patch.template !== design.template) ({ design, changes: moved } = switchTemplate(design, patch.template));
|
||||
for (const [section, variant] of Object.entries(patch.variants ?? {})) {
|
||||
if (!SECTION_TYPES.includes(section as SectionType) || !isVariant(section as SectionType, variant)) throw new ApiError(400, 'VALIDATION', `"${variant}" isn't a layout for ${section}.`);
|
||||
(design.variants as Record<string, string>)[section] = variant;
|
||||
}
|
||||
if (patch.home) {
|
||||
if (new Set(patch.home.map((e) => e.section)).size !== patch.home.length) throw new ApiError(400, 'VALIDATION', 'Each homepage section can be listed once.');
|
||||
design.home = [...patch.home, ...design.home.filter((e) => !patch.home!.some((p) => p.section === e.section)).map((e) => ({ ...e, hidden: true }))];
|
||||
}
|
||||
if (patch.style) {
|
||||
const { header, ...rest } = patch.style;
|
||||
if (header && !(TEMPLATE_HEADERS[design.template] as readonly string[]).includes(header)) throw new ApiError(400, 'VALIDATION', `"${header}" isn't a header for ${design.template}.`);
|
||||
design.style = { ...design.style, ...rest, ...(header ? { header } : {}) };
|
||||
}
|
||||
const data = { template: design.template, variants: design.variants as never, home: design.home as never, style: design.style as never, updatedBy: by.id };
|
||||
await ctx.db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
|
||||
return { design, moved };
|
||||
}
|
||||
|
||||
// ─── Pages and sections ─────────────────────────────────────────────────────────
|
||||
|
||||
const slugSchema = z.string().trim().toLowerCase().regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Lower-case letters, numbers and dashes').max(80);
|
||||
const RESERVED = new Set(['admin', 'api', 'auth', 'preview', 'events', 'home', 'sitemap.xml', 'robots.txt', 'uploads']);
|
||||
|
||||
const pagePatch = z.object({
|
||||
title: z.string().trim().min(1).max(120).optional(),
|
||||
slug: slugSchema.optional(),
|
||||
seoTitle: z.string().trim().max(70).nullable().optional(),
|
||||
description: z.string().trim().max(300).nullable().optional(),
|
||||
navLabel: z.string().trim().max(40).nullable().optional(),
|
||||
inNav: z.boolean().optional(),
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
imageId: z.string().uuid().nullable().optional(),
|
||||
});
|
||||
|
||||
export async function listPages(ctx: Ctx) {
|
||||
const pages = await ctx.db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }] });
|
||||
return pages.map((p) => ({ id: p.id, kind: p.kind, slug: p.slug, title: p.title, inNav: p.inNav, position: p.position, path: p.kind === 'home' ? '/' : `/${p.slug}` }));
|
||||
}
|
||||
|
||||
export async function getPage(ctx: Ctx, id: string) {
|
||||
const page = await ctx.db.page.findUnique({ where: { id } });
|
||||
if (!page || page.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That page doesn\'t exist.');
|
||||
const sections = await ctx.db.section.findMany({ where: { pageId: id }, orderBy: { position: 'asc' } });
|
||||
return { ...page, sections };
|
||||
}
|
||||
|
||||
async function slugFree(ctx: Ctx, slug: string, except?: string) {
|
||||
if (RESERVED.has(slug)) throw new ApiError(400, 'VALIDATION', `"${slug}" is used by the site itself. Choose another address.`, { slug: 'Used by the site itself' });
|
||||
const other = await ctx.db.page.findFirst({ where: { slug, ...(except ? { NOT: { id: except } } : {}) } });
|
||||
if (other && !other.archivedAt) throw new ApiError(409, 'SLUG_TAKEN', 'Another page already has that address.', { slug: 'Another page has it' });
|
||||
if (other) await ctx.db.page.update({ where: { id: other.id }, data: { slug: `${other.slug}-${other.id.slice(0, 6)}` } });
|
||||
}
|
||||
|
||||
export async function savePage(ctx: Ctx, id: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, id);
|
||||
const patch = check(pagePatch, body);
|
||||
if (page.kind === 'home') delete patch.slug;
|
||||
if (patch.slug && patch.slug !== page.slug) await slugFree(ctx, patch.slug, id);
|
||||
await ctx.db.page.update({ where: { id }, data: { ...patch, updatedBy: by.id } });
|
||||
return getPage(ctx, id);
|
||||
}
|
||||
|
||||
/** A custom page (§3, "Pages from blocks"), starting with one text block. */
|
||||
export async function createPage(ctx: Ctx, body: unknown, by: Who) {
|
||||
const p = check(z.object({ title: z.string().trim().min(1).max(120), slug: slugSchema }), body);
|
||||
await slugFree(ctx, p.slug);
|
||||
const last = await ctx.db.page.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
|
||||
const page = await ctx.db.page.create({ data: { kind: 'custom', slug: p.slug, title: p.title, position: (last?.position ?? 0) + 1, updatedBy: by.id } });
|
||||
await ctx.db.section.create({ data: { pageId: page.id, type: 'text', position: 0, data: { heading: null, body: '' }, updatedBy: by.id } });
|
||||
return getPage(ctx, page.id);
|
||||
}
|
||||
|
||||
/** Archive, never delete (§4): restored by Discard or by restoring a version. The home page stays. */
|
||||
export async function archivePage(ctx: Ctx, id: string, by: Who) {
|
||||
const page = await getPage(ctx, id);
|
||||
if (page.kind === 'home') throw new ApiError(400, 'HOME', 'The home page can\'t be removed.');
|
||||
await ctx.db.page.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
|
||||
}
|
||||
|
||||
function schemaFor(type: string): z.ZodType {
|
||||
const s = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
|
||||
if (!s) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a section or block.`);
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* The home page's section of `type` (one each; its layout is the design's, §3), created the first
|
||||
* time it's saved.
|
||||
*/
|
||||
export async function saveHomeSection(ctx: Ctx, pageId: string, type: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
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 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 } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
const blockPatch = z.object({ data: z.unknown().optional(), variant: z.string().max(40).nullable().optional(), hidden: z.boolean().optional() });
|
||||
|
||||
/** The blocks of any other page: add, change, move, remove. */
|
||||
export async function addBlock(ctx: Ctx, pageId: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
if (page.kind === 'home') throw new ApiError(400, 'VALIDATION', 'The home page has its sections; blocks are for the other pages.');
|
||||
const { type } = check(z.object({ type: z.string() }), body);
|
||||
if (!isBlockType(type)) throw new ApiError(400, 'VALIDATION', `"${type}" isn't a block.`);
|
||||
const data = check(schemaFor(type), type === 'quote' ? { quote: 'Your quote here' } : type === 'cta' ? { heading: 'Your heading here' } : {});
|
||||
await ctx.db.section.create({ data: { pageId, type, position: page.sections.length, data: data as never, updatedBy: by.id } });
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
export async function saveBlock(ctx: Ctx, pageId: string, sectionId: string, body: unknown, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
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);
|
||||
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 } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
export async function moveBlock(ctx: Ctx, pageId: string, sectionId: string, direction: 'up' | 'down', by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
const list = [...page.sections];
|
||||
const i = list.findIndex((x) => x.id === sectionId);
|
||||
const j = direction === 'up' ? i - 1 : i + 1;
|
||||
if (i < 0 || j < 0 || j >= list.length) return page;
|
||||
[list[i], list[j]] = [list[j]!, list[i]!];
|
||||
for (const [n, s] of list.entries()) await ctx.db.section.update({ where: { id: s.id }, data: { position: n, updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
export async function removeBlock(ctx: Ctx, pageId: string, sectionId: string, by: Who) {
|
||||
const page = await getPage(ctx, pageId);
|
||||
if (!page.sections.some((x) => x.id === sectionId)) throw new ApiError(404, 'NOT_FOUND', 'That block doesn\'t exist.');
|
||||
await ctx.db.section.delete({ where: { id: sectionId } });
|
||||
await ctx.db.page.update({ where: { id: pageId }, data: { updatedBy: by.id } });
|
||||
return getPage(ctx, pageId);
|
||||
}
|
||||
|
||||
// ─── Ministries and leaders ─────────────────────────────────────────────────────
|
||||
|
||||
const ministrySchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
slug: slugSchema.optional(),
|
||||
summary: z.string().trim().max(300).nullable().default(null),
|
||||
body: z.string().trim().max(8000).nullable().default(null),
|
||||
imageId: z.string().uuid().nullable().default(null),
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
});
|
||||
|
||||
const leaderSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
role: z.string().trim().max(120).nullable().default(null),
|
||||
bio: z.string().trim().max(4000).nullable().default(null),
|
||||
photoId: z.string().uuid().nullable().default(null),
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
});
|
||||
|
||||
const slugify = (s: string) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'ministry';
|
||||
|
||||
export async function listMinistries(ctx: Ctx) {
|
||||
return ctx.db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
|
||||
}
|
||||
|
||||
export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, by: Who) {
|
||||
const m = check(ministrySchema, body);
|
||||
const slug = m.slug ?? slugify(m.name);
|
||||
const clash = await ctx.db.ministry.findFirst({ where: { slug, ...(id ? { NOT: { id } } : {}) } });
|
||||
if (clash) throw new ApiError(409, 'SLUG_TAKEN', 'Another ministry already has that name.', { name: 'Another ministry has it' });
|
||||
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
|
||||
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.');
|
||||
return ctx.db.ministry.update({ where: { id }, data });
|
||||
}
|
||||
const last = await ctx.db.ministry.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
|
||||
return ctx.db.ministry.create({ data: { ...data, position: m.position ?? (last?.position ?? -1) + 1 } });
|
||||
}
|
||||
|
||||
export async function archiveMinistry(ctx: Ctx, id: string, by: Who) {
|
||||
await ctx.db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
|
||||
}
|
||||
|
||||
export async function listLeaders(ctx: Ctx) {
|
||||
return ctx.db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] });
|
||||
}
|
||||
|
||||
export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: Who) {
|
||||
const l = check(leaderSchema, body);
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
|
||||
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.');
|
||||
return ctx.db.leader.update({ where: { id }, data });
|
||||
}
|
||||
const last = await ctx.db.leader.findFirst({ where: { archivedAt: null }, orderBy: { position: 'desc' } });
|
||||
return ctx.db.leader.create({ data: { ...data, position: l.position ?? (last?.position ?? -1) + 1 } });
|
||||
}
|
||||
|
||||
export async function archiveLeader(ctx: Ctx, id: string, by: Who) {
|
||||
await ctx.db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), updatedBy: by.id } });
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* The media library and storage (WEBSITE-1.0-PLAN §10, ROADMAP-v3 §10): uploads of photos (JPEG,
|
||||
* PNG, WebP), checked by their bytes, not their name. 5 GB included; the licence's
|
||||
* `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.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
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 { mediaUrl } from '../site/snapshot.js';
|
||||
|
||||
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
||||
|
||||
type Kind = { ext: string; mime: string };
|
||||
|
||||
/** What the bytes are, whatever the name says. */
|
||||
export function sniff(b: Buffer): Kind | null {
|
||||
if (b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { ext: 'jpg', mime: 'image/jpeg' };
|
||||
if (b.length > 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: 'png', mime: 'image/png' };
|
||||
if (b.length > 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { ext: 'webp', mime: 'image/webp' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Width and height from the file's header (PNG, JPEG, WebP), or nulls. */
|
||||
export function dimensions(b: Buffer, kind: Kind): { width: number | null; height: number | null } {
|
||||
try {
|
||||
if (kind.ext === 'png') return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
|
||||
if (kind.ext === 'webp') {
|
||||
const chunk = b.toString('ascii', 12, 16);
|
||||
if (chunk === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) };
|
||||
if (chunk === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
|
||||
if (chunk === 'VP8L') {
|
||||
const bits = b.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
}
|
||||
if (kind.ext === 'jpg') {
|
||||
let i = 2;
|
||||
while (i < b.length) {
|
||||
if (b[i] !== 0xff) break;
|
||||
const marker = b[i + 1]!;
|
||||
const len = b.readUInt16BE(i + 2);
|
||||
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { height: b.readUInt16BE(i + 5), width: b.readUInt16BE(i + 7) };
|
||||
i += 2 + len;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A header we can't read: no dimensions, the image still shows.
|
||||
}
|
||||
return { width: null, height: null };
|
||||
}
|
||||
|
||||
export async function storage(ctx: Ctx): Promise<{ usedBytes: number; limitBytes: number; full: boolean; percent: number }> {
|
||||
const [sum, token, installId] = await Promise.all([
|
||||
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
|
||||
ctx.settings.get('hub_licence'),
|
||||
ctx.settings.get('hub_install_id'),
|
||||
]);
|
||||
const claims = verifyToken(token, hubPublicKey(ctx)) as { installId?: string; limits?: { storageBytes?: number } } | null;
|
||||
const fromLicence = claims && claims.installId === installId ? claims.limits?.storageBytes : undefined;
|
||||
const limitBytes = typeof fromLicence === 'number' ? fromLicence : INCLUDED_STORAGE_BYTES;
|
||||
const usedBytes = sum._sum.bytes ?? 0;
|
||||
return { usedBytes, limitBytes, full: usedBytes >= limitBytes, percent: limitBytes ? Math.min(100, Math.round((usedBytes / limitBytes) * 100)) : 100 };
|
||||
}
|
||||
|
||||
export const uploadDir = (ctx: Ctx) => path.resolve(ctx.config.uploadDir ?? defaultUploadDir());
|
||||
|
||||
export async function upload(ctx: Ctx, body: Buffer, alt: string, by: string) {
|
||||
if (!body.length) throw new ApiError(400, 'EMPTY', 'Choose a photo to upload.');
|
||||
if (body.length > MAX_UPLOAD_BYTES) throw new ApiError(413, 'TOO_LARGE', 'That file is larger than 15 MB. Make it smaller and try again.');
|
||||
const kind = sniff(body);
|
||||
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.');
|
||||
}
|
||||
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 } });
|
||||
return { ...row, url: mediaUrl(row.filename) };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Shared previews (WEBSITE-1.0-PLAN §4): a link for someone without an account (the pastor), that
|
||||
* shows the working copy as it is when opened, for 7 days or until revoked. It can't edit or
|
||||
* publish, and its pages are `noindex`. Only the token's hash is stored; the link is shown once.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
|
||||
export const PREVIEW_DAYS = 7;
|
||||
|
||||
export async function createPreviewLink(ctx: Ctx, by: { id: string; role: string }) {
|
||||
const token = randomToken();
|
||||
const now = ctx.now();
|
||||
const row = await ctx.db.previewLink.create({ data: { tokenHash: hashToken(token), createdBy: by.id, createdAt: now, expiresAt: new Date(now.getTime() + PREVIEW_DAYS * 864e5) } });
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_created', targetType: 'preview_link', targetId: row.id });
|
||||
return { id: row.id, url: `${ctx.config.publicUrl}/preview/${token}`, expiresAt: row.expiresAt.toISOString() };
|
||||
}
|
||||
|
||||
export async function listPreviewLinks(ctx: Ctx) {
|
||||
const now = ctx.now();
|
||||
const rows = await ctx.db.previewLink.findMany({ orderBy: { createdAt: 'desc' } });
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
return rows.map((r) => ({
|
||||
id: r.id, createdAt: r.createdAt.toISOString(), expiresAt: r.expiresAt.toISOString(), by: names.get(r.createdBy) ?? null,
|
||||
active: !r.revokedAt && r.expiresAt > now, revokedAt: r.revokedAt?.toISOString() ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function revokePreviewLink(ctx: Ctx, id: string, by: { id: string; role: string }) {
|
||||
const row = await ctx.db.previewLink.findUnique({ where: { id } });
|
||||
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That preview link doesn\'t exist.');
|
||||
await ctx.db.previewLink.update({ where: { id }, data: { revokedAt: ctx.now() } });
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'preview_link_revoked', targetType: 'preview_link', targetId: id });
|
||||
}
|
||||
|
||||
export async function previewTokenValid(ctx: Ctx, token: string | undefined): Promise<boolean> {
|
||||
if (!token || token.length > 200) return false;
|
||||
const row = await ctx.db.previewLink.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
return !!row && !row.revokedAt && row.expiresAt > ctx.now();
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The admin API (WEBSITE-1.0-PLAN §4, §10), under /api/v1/admin, signed in through Accounts.
|
||||
* Roles: a Viewer reads; an Editor (and Admin, Owner) changes anything, publishes and shares
|
||||
* previews; a Ministry leader changes only their own ministry, and their changes wait for an
|
||||
* Editor or above to publish (decision 11). Every change comes from the site itself (sameOrigin).
|
||||
*/
|
||||
import express, { type Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { atLeast, requireRole } from '../auth/sessions.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { ApiError, handle, sameOrigin } from '../http.js';
|
||||
import { buildPalette } from '../site/palette.js';
|
||||
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 { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
|
||||
|
||||
const who = (req: Request) => ({ id: req.signed!.user.id, role: req.signed!.user.role });
|
||||
const param = (req: Request, name: string) => String(req.params[name] ?? '');
|
||||
|
||||
export function adminRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
|
||||
r.use(requireRole(ctx, 'viewer'));
|
||||
const json = express.json({ limit: '256kb' });
|
||||
const editor = requireRole(ctx, 'editor');
|
||||
|
||||
r.get('/me', handle((req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
|
||||
|
||||
/** 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([
|
||||
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),
|
||||
]);
|
||||
const palette = church ? buildPalette(church.branding.colours.primary, church.branding.colours.accent) : null;
|
||||
return {
|
||||
pending: pending.length,
|
||||
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: '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' },
|
||||
],
|
||||
};
|
||||
}));
|
||||
|
||||
// ─── Design ───
|
||||
r.get('/design', handle(async () => ({ design: await content.getDesign(ctx), options: { variants: TEMPLATE_VARIANTS, headers: TEMPLATE_HEADERS, home: TEMPLATE_HOME_ORDER } })));
|
||||
r.put('/design', editor, json, handle((req) => content.saveDesign(ctx, req.body, who(req))));
|
||||
|
||||
// ─── Pages ───
|
||||
r.get('/pages', handle(() => content.listPages(ctx)));
|
||||
r.post('/pages', editor, json, handle((req) => content.createPage(ctx, req.body, who(req))));
|
||||
r.get('/pages/:id', handle((req) => content.getPage(ctx, param(req, 'id'))));
|
||||
r.put('/pages/:id', editor, json, handle((req) => content.savePage(ctx, param(req, 'id'), req.body, who(req))));
|
||||
r.delete('/pages/:id', editor, handle(async (req) => { await content.archivePage(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
r.put('/pages/:id/home/:type', editor, json, handle((req) => content.saveHomeSection(ctx, param(req, 'id'), param(req, 'type'), req.body, who(req))));
|
||||
r.post('/pages/:id/blocks', editor, json, handle((req) => content.addBlock(ctx, param(req, 'id'), req.body, who(req))));
|
||||
r.put('/pages/:id/blocks/:sid', editor, json, handle((req) => content.saveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body, who(req))));
|
||||
r.post('/pages/:id/blocks/:sid/move', editor, json, handle((req) => content.moveBlock(ctx, param(req, 'id'), param(req, 'sid'), req.body?.direction === 'up' ? 'up' : 'down', who(req))));
|
||||
r.delete('/pages/:id/blocks/:sid', editor, handle((req) => content.removeBlock(ctx, param(req, 'id'), param(req, 'sid'), who(req))));
|
||||
|
||||
// ─── Ministries (a Ministry leader: their own only) and leaders ───
|
||||
r.get('/ministries', handle(() => content.listMinistries(ctx)));
|
||||
r.post('/ministries', editor, json, handle((req) => content.saveMinistry(ctx, null, req.body, who(req))));
|
||||
r.put('/ministries/:id', json, handle((req) => {
|
||||
const s = req.signed!;
|
||||
if (!atLeast(s.user.role, 'editor') && !(s.user.role === 'ministry_leader' && s.user.ministryId === param(req, 'id'))) {
|
||||
throw new ApiError(403, 'FORBIDDEN', 'You can change your own ministry only.');
|
||||
}
|
||||
return content.saveMinistry(ctx, param(req, 'id'), req.body, who(req));
|
||||
}));
|
||||
r.delete('/ministries/:id', editor, handle(async (req) => { await content.archiveMinistry(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
r.get('/leaders', handle(() => content.listLeaders(ctx)));
|
||||
r.post('/leaders', editor, json, handle((req) => content.saveLeader(ctx, null, req.body, who(req))));
|
||||
r.put('/leaders/:id', editor, json, handle((req) => content.saveLeader(ctx, param(req, 'id'), req.body, who(req))));
|
||||
r.delete('/leaders/:id', editor, handle(async (req) => { await content.archiveLeader(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
|
||||
// ─── 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 })) };
|
||||
}));
|
||||
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)));
|
||||
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);
|
||||
if (!m) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
|
||||
return { id: m.id, alt: m.alt };
|
||||
}));
|
||||
|
||||
// ─── Publish, discard, restore, versions, shared previews (§4) ───
|
||||
r.get('/changes', handle(() => changes(ctx)));
|
||||
r.post('/publish', editor, json, handle(async (req) => {
|
||||
const pending = await changes(ctx);
|
||||
const first = !(await ctx.db.siteVersion.findFirst());
|
||||
if (!pending.length && !first) throw new ApiError(409, 'NOTHING_TO_PUBLISH', 'There are no changes to publish.');
|
||||
const note = typeof req.body?.note === 'string' && req.body.note.trim() ? req.body.note.trim().slice(0, 500) : null;
|
||||
const v = await publish(ctx, who(req), note);
|
||||
return { number: v.number, publishedAt: v.publishedAt.toISOString(), changes: pending.length };
|
||||
}));
|
||||
r.post('/discard', editor, json, handle((req) => discard(ctx, String(req.body?.key ?? ''), who(req))));
|
||||
r.get('/versions', handle(async () => {
|
||||
const rows = await ctx.db.siteVersion.findMany({ orderBy: { number: 'desc' }, take: 100, select: { number: true, publishedAt: true, publishedBy: true, note: true } });
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
return rows.map((v) => ({ number: v.number, publishedAt: v.publishedAt.toISOString(), by: names.get(v.publishedBy) ?? null, note: v.note }));
|
||||
}));
|
||||
r.post('/versions/:n/restore', editor, handle((req) => restore(ctx, Number(param(req, 'n')), who(req))));
|
||||
r.get('/preview-links', editor, handle(() => listPreviewLinks(ctx)));
|
||||
r.post('/preview-links', editor, handle((req) => createPreviewLink(ctx, who(req))));
|
||||
r.delete('/preview-links/:id', editor, handle(async (req) => { await revokePreviewLink(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* The Express app (docs/WEBSITE-1.0-PLAN.md §1). Everything is under /api, so the site and its API
|
||||
* share one address (as Events and Accounts): nginx sends /api to this backend and the rest to Next.js.
|
||||
*
|
||||
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
|
||||
* /api/v1/site/… the public site (what visitors see: the latest published version)
|
||||
* /api/uploads/… the church's uploaded images
|
||||
* /api/auth/… signing in to the admin through the church's Accounts
|
||||
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
|
||||
* /api/links/v1/… Connect and Disconnect with the church's other products
|
||||
* /api/v1/admin/… the admin (signed in, by role)
|
||||
*
|
||||
* To come (§1): the admin's content, publish and preview links, uploading, the event feed.
|
||||
*/
|
||||
import path from 'node:path';
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { authRouter } from './auth/routes.js';
|
||||
import { adminRouter } from './admin/routes.js';
|
||||
import { previewTokenValid } from './admin/previewLinks.js';
|
||||
import { atLeast, currentSession } from './auth/sessions.js';
|
||||
import { dbUp } from './hub/client.js';
|
||||
import { ApiError, handle, sendError } from './http.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
import { linksRouter } from './links/routes.js';
|
||||
import { defaultUploadDir } from './demo/demoChurch.js';
|
||||
import { previewContent, siteContent } from './site/content.js';
|
||||
import { siteStatus } from './site/status.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
|
||||
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
// The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11).
|
||||
res.setHeader('X-Robots-Tag', 'noindex');
|
||||
next();
|
||||
});
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
const db = await dbUp(ctx);
|
||||
res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'website', version: appVersion(), db });
|
||||
});
|
||||
|
||||
const site = express.Router();
|
||||
site.get('/status', handle(() => siteStatus(ctx)));
|
||||
// The preview (§4): the working copy, for a signed-in admin or a shared preview link. Never cached.
|
||||
site.get('/preview', handle(async (req, res) => {
|
||||
const signed = await currentSession(ctx, req);
|
||||
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') } };
|
||||
}));
|
||||
site.get('/content', handle(async (_req, res) => {
|
||||
// Short: Publish shows within a minute even where a proxy caches.
|
||||
res.set('Cache-Control', 'public, max-age=30');
|
||||
return siteContent(ctx);
|
||||
}));
|
||||
app.use('/api/v1/site', site);
|
||||
|
||||
// Uploaded files: never a directory listing, never outside the folder (express.static checks).
|
||||
app.use('/api/uploads', express.static(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), {
|
||||
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '7d',
|
||||
setHeaders: (res) => {
|
||||
// An uploaded SVG is shown as an image, never run as a page.
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
},
|
||||
}));
|
||||
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
|
||||
app.use('/api/v1/admin', adminRouter(ctx));
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
|
||||
});
|
||||
|
||||
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
if (res.headersSent) return next(err);
|
||||
if (err instanceof ApiError) return sendError(res, err);
|
||||
const e = err as { type?: string; status?: number };
|
||||
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
|
||||
// A missing upload (express.static), or another known client error.
|
||||
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
|
||||
return sendError(res, err);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The church's Accounts, as this site's OIDC client (WEBSITE-1.0-PLAN §1, §10), built on
|
||||
* `@crosscode/auth-client` from the Accounts link (links/connect.ts). Its address is the one the
|
||||
* Hub listed; the client id is this site's Hub install id and the client secret comes from the
|
||||
* link's secret, so there's no `.env` setting for any of it (as Cross Events 3.x).
|
||||
*/
|
||||
import type * as AuthClient from '@crosscode/auth-client';
|
||||
import type { AccountsClient } from '@crosscode/auth-client';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
|
||||
export type AuthClientModule = typeof AuthClient;
|
||||
|
||||
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
|
||||
|
||||
export class AccountsUnavailable extends ApiError {
|
||||
constructor(message: string) {
|
||||
super(503, 'ACCOUNTS_UNAVAILABLE', message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The Accounts link, or null while the Website isn't linked to Accounts. */
|
||||
export async function accountsLink(ctx: Ctx) {
|
||||
return ctx.db.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
|
||||
}
|
||||
|
||||
const cache = new WeakMap<Ctx, { key: string; client: Promise<AccountsClient> }>();
|
||||
|
||||
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
|
||||
export async function accounts(ctx: Ctx): Promise<AccountsClient> {
|
||||
const link = await accountsLink(ctx);
|
||||
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet. It links by itself within 15 minutes of being installed.');
|
||||
const clientId = await ctx.settings.get('hub_install_id');
|
||||
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.');
|
||||
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
|
||||
let hit = cache.get(ctx);
|
||||
if (!hit || hit.key !== key) {
|
||||
const client = ctx.authClient().then((m) => m.accountsClient({
|
||||
accountsUrl: link.url,
|
||||
productUrl: ctx.config.publicUrl,
|
||||
clientId,
|
||||
linkSecret: ctx.secrets.decrypt(link.secret),
|
||||
allowInsecure: !ctx.config.production && link.url.startsWith('http:'),
|
||||
}));
|
||||
// A failed discovery (Accounts down for a moment) is tried again next time.
|
||||
client.catch(() => { if (cache.get(ctx)?.key === key) cache.delete(ctx); });
|
||||
hit = { key, client };
|
||||
cache.set(ctx, hit);
|
||||
}
|
||||
try {
|
||||
return await hit.client;
|
||||
} catch (e) {
|
||||
throw new AccountsUnavailable(`The church's Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Signing in to the Website's admin through the church's Accounts (WEBSITE-1.0-PLAN §10, as Cross
|
||||
* Events 3.x), under /api:
|
||||
*
|
||||
* GET /auth/signin?returnTo=…[&mfa=1] PKCE + state in a short-lived cookie, then off to Accounts
|
||||
* GET /auth/callback back from Accounts: the Website's own session, then returnTo
|
||||
* GET /auth/me who's signed in (the admin pages ask)
|
||||
* POST /auth/signout ends this session, then Accounts' sign-out (all the church's sites)
|
||||
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
|
||||
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
|
||||
*
|
||||
* Who may use the admin is the Website's own business (roles are never in the claims). The first
|
||||
* Owner is whoever signs in with the church's admin email from the Hub (HUB_ADMIN_EMAIL), verified
|
||||
* in Accounts, while the site has no Owner; everyone else is added by an Owner or Admin.
|
||||
*/
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { WebsiteRole } from '../generated/prisma/client.js';
|
||||
import { handle, sendError } from '../http.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { accounts, AccountsUnavailable } from './accounts.js';
|
||||
import { cookieOptions, currentSession, needsTwoFactor, readCookies, SESSION_COOKIE, startSession } from './sessions.js';
|
||||
|
||||
const PENDING_COOKIE = 'ccw_signin';
|
||||
const MFA_COOKIE = 'ccw_signin_mfa';
|
||||
const COOKIE_PATH = '/api/auth';
|
||||
const PENDING_MINUTES = 10;
|
||||
|
||||
/** A page of this site, absolute (in development the API and the pages are on different ports). */
|
||||
const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${path}`;
|
||||
|
||||
/** The problem page: a short reason and "Try again" with the same return path. */
|
||||
const problem = (ctx: Ctx, res: Response, code: string, returnTo = '/admin') =>
|
||||
res.redirect(303, page(ctx, `/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
|
||||
|
||||
type UserRow = { id: string; name: string; email: string; role: WebsiteRole };
|
||||
|
||||
/**
|
||||
* The Website user for a sign-in: by `sub`; else the first Owner, when the site has none and this is
|
||||
* the Hub's admin email (verified); else nobody (no access to this admin).
|
||||
*/
|
||||
export async function userForClaims(ctx: Ctx, claims: IdentityClaims): Promise<{ user: UserRow | null; created?: boolean }> {
|
||||
const known = await ctx.db.websiteUser.findUnique({ where: { id: claims.sub } });
|
||||
if (known) {
|
||||
const user = await ctx.db.websiteUser.update({ where: { id: known.id }, data: { name: claims.name, email: claims.email.toLowerCase(), lastSignInAt: ctx.now() } });
|
||||
return { user };
|
||||
}
|
||||
const adminEmail = ctx.config.hubAdminEmail;
|
||||
if (!adminEmail || !claims.email_verified || claims.email.toLowerCase() !== adminEmail) return { user: null };
|
||||
if (await ctx.db.websiteUser.findFirst({ where: { role: 'owner' } })) return { user: null };
|
||||
const user = await ctx.db.websiteUser.create({
|
||||
data: { id: claims.sub, name: claims.name, email: claims.email.toLowerCase(), role: 'owner', lastSignInAt: ctx.now() },
|
||||
});
|
||||
return { user, created: true };
|
||||
}
|
||||
|
||||
export function authRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
|
||||
r.get('/auth/signin', async (req, res) => {
|
||||
const returnTo = safeReturnPath(req.query.returnTo);
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const requireTwoFactor = req.query.mfa === '1';
|
||||
const { url, cookie } = await auth.startSignIn(returnTo, { requireTwoFactor });
|
||||
const opts = { ...cookieOptions(ctx, COOKIE_PATH), maxAge: PENDING_MINUTES * 60e3 };
|
||||
res.cookie(PENDING_COOKIE, cookie, opts);
|
||||
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', opts);
|
||||
else res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
return res.redirect(303, url);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE', returnTo);
|
||||
console.error('[auth] Starting a sign-in failed:', e);
|
||||
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
|
||||
}
|
||||
});
|
||||
|
||||
r.get(OIDC_CLIENT_PATHS.callback.replace(/^\/api/, ''), async (req, res) => {
|
||||
const cookies = readCookies(req);
|
||||
const askedForTwoFactor = cookies[MFA_COOKIE] === '1';
|
||||
res.clearCookie(PENDING_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
let result: Awaited<ReturnType<Awaited<ReturnType<typeof accounts>>['finishSignIn']>>;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
result = await auth.finishSignIn(new URL(req.originalUrl, ctx.config.publicUrl), cookies[PENDING_COOKIE]);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE');
|
||||
const code = (e as { code?: string }).code;
|
||||
// The person pressed Cancel at Accounts, or the pending cookie expired.
|
||||
if (req.query.error === 'access_denied') return res.redirect(303, page(ctx, '/'));
|
||||
return problem(ctx, res, code === 'NO_PENDING' ? 'EXPIRED' : 'SIGNIN_FAILED');
|
||||
}
|
||||
const { claims, returnTo, idToken } = result;
|
||||
const { user, created } = await userForClaims(ctx, claims);
|
||||
if (!user) {
|
||||
await audit(ctx, { actorId: claims.sub, actorRole: 'none', action: 'admin_sign_in_refused', targetType: 'website_user', targetId: claims.sub, ip: clientIp(req) });
|
||||
return problem(ctx, res, 'NO_ACCESS', returnTo);
|
||||
}
|
||||
const mfa = claims.amr.includes('mfa');
|
||||
if (!mfa && (await needsTwoFactor(ctx, user.role))) {
|
||||
// Once: ask Accounts again with a second step. If it still comes back without one, say why.
|
||||
if (askedForTwoFactor) return problem(ctx, res, 'TWO_FACTOR_NEEDED', returnTo);
|
||||
return res.redirect(303, page(ctx, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`));
|
||||
}
|
||||
// Accounts' session id, when its token carries one (not part of crosscode.identity/1's claims).
|
||||
const sid = (claims as unknown as { sid?: string }).sid ?? null;
|
||||
await startSession(ctx, res, { userId: user.id, sid, mfa, idToken });
|
||||
await audit(ctx, { actorId: user.id, actorRole: user.role, action: created ? 'first_owner_signed_in' : 'admin_signed_in', targetType: 'website_user', targetId: user.id, ip: clientIp(req) });
|
||||
return res.redirect(303, page(ctx, returnTo));
|
||||
});
|
||||
|
||||
r.get('/auth/me', handle(async (req, res) => {
|
||||
const s = await currentSession(ctx, req);
|
||||
if (!s) {
|
||||
res.status(401).json({ error: { code: 'SIGNED_OUT', message: 'Please sign in.' } });
|
||||
return undefined;
|
||||
}
|
||||
return { user: s.user, mfa: s.mfa };
|
||||
}));
|
||||
|
||||
r.post('/auth/signout', async (req, res) => {
|
||||
const s = await currentSession(ctx, req).catch(() => null);
|
||||
res.clearCookie(SESSION_COOKIE, cookieOptions(ctx));
|
||||
if (s) {
|
||||
await ctx.db.session.delete({ where: { id: s.sessionId } }).catch(() => {});
|
||||
await audit(ctx, { actorId: s.user.id, actorRole: s.user.role, action: 'admin_signed_out', targetType: 'website_user', targetId: s.user.id, ip: clientIp(req) });
|
||||
}
|
||||
// Then Accounts, so the person is signed out of all the church's sites and comes back here.
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
return res.redirect(303, auth.signOutUrl(s?.idToken ?? undefined));
|
||||
} catch {
|
||||
return res.redirect(303, page(ctx, '/'));
|
||||
}
|
||||
});
|
||||
|
||||
r.post(OIDC_CLIENT_PATHS.backchannelLogout.replace(/^\/api/, ''), express.urlencoded({ extended: false, limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const { sub, sid } = await auth.verifyLogoutToken(String(req.body?.logout_token ?? ''));
|
||||
// That Accounts session's sign-ins here, and any whose session id wasn't known.
|
||||
await ctx.db.session.deleteMany({ where: sid ? { userId: sub, OR: [{ sid }, { sid: null }] } : { userId: sub } });
|
||||
res.set('Cache-Control', 'no-store').status(200).end();
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code;
|
||||
res.status(code === 'BAD_TOKEN' ? 400 : 503).json({ error: 'invalid_request' });
|
||||
}
|
||||
});
|
||||
|
||||
r.post(ACCOUNTS_CALL_PATH.replace(/^\/api/, ''), express.raw({ type: '*/*', limit: '256kb' }), async (req, res) => {
|
||||
let call: AccountsCall;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
call = auth.verifyAccountsCall(req.body as Buffer, req.headers);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return sendError(res, e);
|
||||
return res.status(401).json({ error: { code: (e as { code?: string }).code ?? 'BAD_SIGNATURE', message: (e as Error).message } });
|
||||
}
|
||||
try {
|
||||
return res.json(await handleAccountsCall(ctx, call, req));
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accounts' signed calls. The Website only keeps an admin's name, email and role, so: update the
|
||||
* copy, export it, or remove the person (and their sessions). Someone the Website doesn't know is
|
||||
* answered as done.
|
||||
*/
|
||||
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
|
||||
const user = await ctx.db.websiteUser.findUnique({ where: { id: call.sub } });
|
||||
switch (call.type) {
|
||||
case 'user.updated': {
|
||||
if (user) await ctx.db.websiteUser.update({ where: { id: user.id }, data: { name: call.profile.name, email: call.profile.email.toLowerCase() } });
|
||||
return { schema: IDENTITY_SCHEMA, ok: true };
|
||||
}
|
||||
case 'user.export': {
|
||||
const reply: UserExportReply = {
|
||||
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'website', generatedAt: ctx.now().toISOString(),
|
||||
sections: user ? [{
|
||||
key: 'website_admin',
|
||||
title: 'Your access to the church\'s website admin',
|
||||
records: [{ name: user.name, email: user.email, role: user.role, since: user.createdAt.toISOString(), lastSignIn: user.lastSignInAt?.toISOString() ?? null }],
|
||||
}] : [],
|
||||
};
|
||||
return reply;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
if (user) {
|
||||
await ctx.db.session.deleteMany({ where: { userId: user.id } });
|
||||
await ctx.db.websiteUser.delete({ where: { id: user.id } });
|
||||
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'website_user_deleted', targetType: 'website_user', targetId: user.id, metadata: { role: user.role }, ip: clientIp(req) });
|
||||
}
|
||||
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Admin sessions and roles (WEBSITE-1.0-PLAN §10). The Website keeps its own session after a
|
||||
* sign-in through Accounts: an HttpOnly cookie with a random token, of which only the SHA-256 is
|
||||
* stored. Roles are the Website's own (keyed by the account's `sub`); Accounts never says them.
|
||||
*/
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { WebsiteRole } from '../generated/prisma/client.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
|
||||
export const SESSION_COOKIE = 'ccw_session';
|
||||
|
||||
/** Lowest to highest. A role can do what every role before it can. */
|
||||
export const ROLES: readonly WebsiteRole[] = ['viewer', 'ministry_leader', 'editor', 'admin', 'owner'];
|
||||
export const atLeast = (role: WebsiteRole, min: WebsiteRole) => ROLES.indexOf(role) >= ROLES.indexOf(min);
|
||||
|
||||
/** Roles that need a second step at sign-in (on by default, §10; AppSetting `two_factor_required_for_admins`). */
|
||||
export async function needsTwoFactor(ctx: Ctx, role: WebsiteRole): Promise<boolean> {
|
||||
return atLeast(role, 'admin') && (await ctx.settings.bool('two_factor_required_for_admins', true));
|
||||
}
|
||||
|
||||
export function readCookies(req: Request): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of String(req.headers.cookie || '').split(';')) {
|
||||
const i = part.indexOf('=');
|
||||
if (i > 0) {
|
||||
try {
|
||||
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
||||
} catch {
|
||||
// A cookie this site didn't write: ignored.
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieOptions = (ctx: Ctx, path = '/') => ({ httpOnly: true, sameSite: 'lax' as const, secure: ctx.config.production, path });
|
||||
|
||||
export async function startSession(ctx: Ctx, res: Response, s: { userId: string; sid: string | null; mfa: boolean; idToken: string }) {
|
||||
const token = randomToken();
|
||||
const now = ctx.now();
|
||||
const expiresAt = new Date(now.getTime() + ctx.config.sessionDays * 24 * 3600e3);
|
||||
await ctx.db.session.create({
|
||||
data: { tokenHash: hashToken(token), userId: s.userId, sid: s.sid, mfa: s.mfa, idToken: ctx.secrets.encrypt(s.idToken), createdAt: now, lastSeenAt: now, expiresAt },
|
||||
});
|
||||
res.cookie(SESSION_COOKIE, token, { ...cookieOptions(ctx), expires: expiresAt });
|
||||
}
|
||||
|
||||
export type Signed = {
|
||||
sessionId: string;
|
||||
idToken: string | null;
|
||||
mfa: boolean;
|
||||
user: { id: string; name: string; email: string; role: WebsiteRole; ministryId: string | null };
|
||||
};
|
||||
|
||||
/** The signed-in admin for this request, or null. */
|
||||
export async function currentSession(ctx: Ctx, req: Request): Promise<Signed | null> {
|
||||
const token = readCookies(req)[SESSION_COOKIE];
|
||||
if (!token) return null;
|
||||
const session = await ctx.db.session.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
if (!session) return null;
|
||||
const now = ctx.now();
|
||||
if (session.expiresAt <= now) {
|
||||
await ctx.db.session.delete({ where: { id: session.id } }).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
const user = await ctx.db.websiteUser.findUnique({ where: { id: session.userId } });
|
||||
if (!user) return null;
|
||||
// Seen at most once a minute, so reading pages doesn't write on every request.
|
||||
if (now.getTime() - session.lastSeenAt.getTime() > 60_000) {
|
||||
await ctx.db.session.update({ where: { id: session.id }, data: { lastSeenAt: now } }).catch(() => {});
|
||||
}
|
||||
let idToken: string | null;
|
||||
try {
|
||||
idToken = session.idToken ? ctx.secrets.decrypt(session.idToken) : null;
|
||||
} catch {
|
||||
idToken = null;
|
||||
}
|
||||
return {
|
||||
sessionId: session.id,
|
||||
idToken,
|
||||
mfa: session.mfa,
|
||||
user: { id: user.id, name: user.name, email: user.email, role: user.role, ministryId: user.ministryId },
|
||||
};
|
||||
}
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
signed?: Signed;
|
||||
}
|
||||
}
|
||||
|
||||
/** Only signed-in admins with at least `min`. 401 when signed out, 403 when the role is too low. */
|
||||
export function requireRole(ctx: Ctx, min: WebsiteRole = 'viewer'): RequestHandler {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
currentSession(ctx, req).then((s) => {
|
||||
if (!s) return next(new ApiError(401, 'SIGNED_OUT', 'Please sign in.'));
|
||||
if (!atLeast(s.user.role, min)) return next(new ApiError(403, 'FORBIDDEN', 'Your role on this website can\'t do that.'));
|
||||
req.signed = s;
|
||||
return next();
|
||||
}).catch(next);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The church profile (`crosscode.church/1`) from the church's Accounts (WEBSITE-1.0-PLAN §2): name,
|
||||
* logo, colours, brand style, service times, contact, social, the church's other sites. Accounts
|
||||
* owns it; the Website shows it and never stores it (§2: shared facts aren't drafts). As Events
|
||||
* 3.7's accounts/church.ts: kept in memory for 10 minutes, the last copy kept while Accounts can't
|
||||
* be reached (tried again after a minute).
|
||||
*
|
||||
* Before the Website is linked to Accounts (and in local development) the profile saved in
|
||||
* AppSetting `church_profile_local` is used, if any (`npm run demo` saves the demo church's).
|
||||
*/
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { accountsLink } from '../auth/accounts.js';
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
|
||||
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
const caches = new WeakMap<Ctx, { cached: Cached | null; pending: Promise<Church | null> | null }>();
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
const parsed = churchSchema.safeParse(await res.json());
|
||||
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function localProfile(ctx: Ctx): Promise<Church | null> {
|
||||
const raw = await ctx.settings.json<unknown>('church_profile_local', null);
|
||||
const parsed = raw ? churchSchema.safeParse(raw) : null;
|
||||
return parsed?.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** The church's profile, or null when there's none yet. Never throws. */
|
||||
export async function churchProfile(ctx: Ctx): Promise<Church | null> {
|
||||
let link;
|
||||
try {
|
||||
link = await accountsLink(ctx);
|
||||
} catch {
|
||||
link = null;
|
||||
}
|
||||
if (!link) return localProfile(ctx).catch(() => null);
|
||||
let state = caches.get(ctx);
|
||||
if (!state) caches.set(ctx, (state = { cached: null, pending: null }));
|
||||
const { cached } = state;
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && ctx.now().getTime() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!state.pending) {
|
||||
const last = cached?.url === url ? cached.church : null;
|
||||
const s = state;
|
||||
s.pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
s.cached = { url, church, at: ctx.now().getTime(), ok: true };
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
s.cached = { url, church: last, at: ctx.now().getTime(), ok: false };
|
||||
return last;
|
||||
})
|
||||
.finally(() => { s.pending = null; });
|
||||
}
|
||||
return state.pending;
|
||||
}
|
||||
|
||||
/** `church.changed` from Accounts: fetched again next time (the last copy is shown meanwhile). */
|
||||
export function churchChanged(ctx: Ctx): void {
|
||||
const state = caches.get(ctx);
|
||||
if (state?.cached) state.cached = { ...state.cached, at: 0 };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
|
||||
* whole app against an in-memory database and a stand-in Accounts (tests/support/).
|
||||
*/
|
||||
import type { PrismaClient } from './generated/prisma/client.js';
|
||||
import type { Config } from './lib/config.js';
|
||||
import { Secrets } from './lib/crypto.js';
|
||||
import { Settings } from './lib/settings.js';
|
||||
import { loadAuthClient, type AuthClientModule } from './auth/accounts.js';
|
||||
|
||||
export type Db = PrismaClient;
|
||||
|
||||
export type Ctx = {
|
||||
config: Config;
|
||||
db: Db;
|
||||
secrets: Secrets;
|
||||
settings: Settings;
|
||||
/** `@crosscode/auth-client` (tests give a stand-in). */
|
||||
authClient: () => Promise<AuthClientModule>;
|
||||
now: () => Date;
|
||||
};
|
||||
|
||||
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule> } = {}): Ctx {
|
||||
const secrets = new Secrets(config.secret);
|
||||
const partial = { config, db, secrets } as Ctx;
|
||||
partial.settings = new Settings(partial);
|
||||
partial.authClient = opts.authClient ?? loadAuthClient;
|
||||
partial.now = opts.now ?? (() => new Date());
|
||||
return partial;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* The demo church (WEBSITE-1.0-PLAN §11, "Demo church"): a fictional church, fictional people and
|
||||
* illustrated images (no photos of anyone), loaded into a template for development, the Hub's demo
|
||||
* sites and the crosscode-site screenshots. `npm run demo -- --template bold`.
|
||||
*
|
||||
* It replaces the Website's content (never the admins), so the script refuses on a site that has
|
||||
* been published unless told otherwise.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { CHURCH_SCHEMA, type Church, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { SectionData } from '../site/sections.js';
|
||||
import { publish } from '../site/snapshot.js';
|
||||
import { defaultDesign } from '../site/variants.js';
|
||||
|
||||
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
|
||||
|
||||
export function demoProfile(publicUrl: string): Church {
|
||||
return {
|
||||
schema: CHURCH_SCHEMA,
|
||||
customerId: '00000000-0000-4000-8000-000000000001',
|
||||
updatedAt: '2026-11-25T08:00:00.000Z',
|
||||
name: 'Acacia Hill Church',
|
||||
shortName: 'Acacia Hill',
|
||||
timezone: 'Africa/Johannesburg',
|
||||
locale: 'en-ZA',
|
||||
branding: { logoUrl: null, iconUrl: null, colours: DEMO_COLOURS, style: { fontPairing: null, corners: null } },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: 'sunday', time: '08:30', label: 'Early service', campus: null, note: null },
|
||||
{ day: 'sunday', time: '10:00', label: 'Family service', campus: null, note: 'Kids church during the service' },
|
||||
{ day: 'wednesday', time: '18:30', label: 'Midweek prayer', campus: null, note: null },
|
||||
],
|
||||
contact: {
|
||||
email: 'hello@acaciahill.example',
|
||||
phone: '+27125550123',
|
||||
whatsapp: '+27825550123',
|
||||
address: { line1: '12 Acacia Avenue', line2: null, suburb: 'Westridge', city: 'Pretoria', province: 'Gauteng', postalCode: '0181', country: 'ZA', geo: { lat: -25.7461, lng: 28.1881 } },
|
||||
},
|
||||
social: [
|
||||
{ network: 'facebook', url: 'https://www.facebook.com/acaciahill.example' },
|
||||
{ network: 'youtube', url: 'https://www.youtube.com/@acaciahill.example' },
|
||||
],
|
||||
links: { website: publicUrl, events: null, app: null, accounts: 'https://accounts.acaciahill.example' },
|
||||
} as 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 {
|
||||
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);
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">
|
||||
<defs><linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c(3)}"/><stop offset="1" stop-color="#fffaf0"/></linearGradient></defs>
|
||||
<rect width="${w}" height="${h}" fill="url(#sky)"/>
|
||||
<circle cx="${Math.round(w * (0.2 + (seed % 5) * 0.15))}" cy="${y(0.3)}" r="${Math.round(h * 0.12)}" fill="${c(1)}" opacity="0.85"/>
|
||||
<path d="M0 ${y(0.62)} Q ${w * 0.25} ${y(0.45)} ${w * 0.5} ${y(0.6)} T ${w} ${y(0.55)} V ${h} H 0 Z" fill="${c(2)}"/>
|
||||
<path d="M0 ${y(0.75)} Q ${w * 0.35} ${y(0.6)} ${w * 0.7} ${y(0.74)} T ${w} ${y(0.7)} V ${h} H 0 Z" fill="${c(0)}"/>
|
||||
<path d="M${w * 0.45} ${h} C ${w * 0.5} ${y(0.85)} ${w * 0.6} ${y(0.8)} ${w * 0.62} ${y(0.72)}" stroke="${c(3)}" stroke-width="${Math.round(h * 0.03)}" fill="none" stroke-linecap="round"/>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
type Ids = Record<string, string>;
|
||||
|
||||
async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
|
||||
const items: [string, string, number][] = [
|
||||
['hero', 'The hills behind Acacia Hill at sunrise (illustration)', 0],
|
||||
['collage2', 'A path through the veld (illustration)', 1],
|
||||
['collage3', 'Evening over the valley (illustration)', 2],
|
||||
['welcome', 'The church garden (illustration)', 3],
|
||||
['pastor', 'Illustration standing in for the pastor\'s photo', 4],
|
||||
['invite', 'A sunny Sunday morning (illustration)', 5],
|
||||
['kids', 'Illustration for Kids church', 6],
|
||||
['youth', 'Illustration for Youth', 7],
|
||||
['care', 'Illustration for Care and prayer', 8],
|
||||
['music', 'Illustration for Worship', 9],
|
||||
];
|
||||
const ids: Ids = {};
|
||||
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
|
||||
for (const [key, alt, seed] of items) {
|
||||
const filename = `demo/${key}.svg`;
|
||||
const svg = illustration(seed);
|
||||
fs.writeFileSync(path.join(uploadDir, filename), svg);
|
||||
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt } });
|
||||
ids[key] = row.id;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
|
||||
|
||||
/** Replaces the content with the demo church's on `template`, then publishes it. */
|
||||
export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uploadDir?: string; publishedBy?: string } = {}) {
|
||||
const db = ctx.db;
|
||||
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
|
||||
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'mediaAsset', 'siteVersion', 'siteDesign'] as const) {
|
||||
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
|
||||
}
|
||||
const img = await demoMedia(ctx, uploadDir);
|
||||
const design = defaultDesign(template);
|
||||
await db.siteDesign.create({ data: { id: 1, template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
|
||||
await ctx.settings.set('church_profile_local', JSON.stringify(demoProfile(ctx.config.publicUrl)));
|
||||
|
||||
const home: SectionData = {
|
||||
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: { label: 'Plan your visit', href: '/visit' } },
|
||||
serviceTimes: { heading: 'Join us this Sunday', note: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.' },
|
||||
welcome: {
|
||||
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
|
||||
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
|
||||
imageId: img.welcome!, pastor: { name: 'Pastor Thandi Mokoena', role: 'Lead pastor', quote: 'We would love to meet you. Come and say hello at the welcome table.', photoId: img.pastor! },
|
||||
},
|
||||
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
|
||||
team: { heading: 'Our team', intro: null },
|
||||
events: { heading: 'Coming up', count: 3 },
|
||||
latestMessage: { heading: 'Latest message' },
|
||||
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' }, imageId: img.invite! },
|
||||
};
|
||||
const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [
|
||||
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.', sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
|
||||
{
|
||||
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: 'What to expect on your first Sunday at Acacia Hill Church.', sections: [
|
||||
{ type: 'text', data: { heading: 'What to expect', body: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.' } },
|
||||
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.', imageId: img.kids, button: null } },
|
||||
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Send us a WhatsApp and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'about', slug: 'about', title: 'About us', position: 2, description: 'Our story, what we believe and what we value.', sections: [
|
||||
{ type: 'text', data: { heading: 'Our story', body: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.' } },
|
||||
{ type: 'quote', data: { quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' } },
|
||||
],
|
||||
},
|
||||
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: 'Kids, youth, worship, care and prayer at Acacia Hill.', sections: [] },
|
||||
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: 'The team who lead Acacia Hill Church.', sections: [] },
|
||||
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: 'What is coming up at Acacia Hill Church.', sections: [] },
|
||||
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: 'Sunday messages from Acacia Hill Church.', sections: [] },
|
||||
{
|
||||
kind: 'give', slug: 'give', title: 'Give', position: 7, description: 'How to give to Acacia Hill Church.', sections: [
|
||||
{ type: 'text', data: { heading: 'Giving', body: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).' } },
|
||||
],
|
||||
},
|
||||
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: 'Find Acacia Hill Church in Westridge, Pretoria.', sections: [] },
|
||||
];
|
||||
for (const p of pages) {
|
||||
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } });
|
||||
let i = 0;
|
||||
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } });
|
||||
}
|
||||
|
||||
const ministries: [string, string, string, string][] = [
|
||||
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.', img.kids!],
|
||||
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.', img.youth!],
|
||||
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.', img.music!],
|
||||
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.', img.care!],
|
||||
];
|
||||
let n = 0;
|
||||
for (const [slug, name, summary, imageId] of ministries) await db.ministry.create({ data: { slug, name, summary, imageId, position: n++ } });
|
||||
const leaders: [string, string, string | null][] = [
|
||||
['Thandi Mokoena', 'Lead pastor', img.pastor!],
|
||||
['Pieter van Wyk', 'Associate pastor', null],
|
||||
['Lerato Dlamini', 'Kids and families', null],
|
||||
['Johan Botha', 'Worship', null],
|
||||
];
|
||||
n = 0;
|
||||
for (const [name, role, photoId] of leaders) await db.leader.create({ data: { name, role, photoId, position: n++ } });
|
||||
|
||||
const now = ctx.now();
|
||||
const day = 864e5;
|
||||
const series = await db.messageSeries.create({ data: { slug: 'hope-for-today', title: 'Hope for today' } });
|
||||
const messages: [string, string, number][] = [['hope-that-holds', 'A hope that holds', 3], ['bread-for-the-road', 'Bread for the road', 10], ['the-good-shepherd', 'The good shepherd', 17]];
|
||||
for (const [slug, title, ago] of messages) {
|
||||
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker: 'Pastor Thandi Mokoena', passage: 'Psalm 23', seriesId: series.id, publishedAt: now } });
|
||||
}
|
||||
const events: [string, string, number, string][] = [
|
||||
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
|
||||
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
|
||||
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
|
||||
];
|
||||
for (const [slug, title, inDays, description] of events) {
|
||||
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
|
||||
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: 'Acacia Hill Church', description, publishedAt: now } });
|
||||
}
|
||||
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, `Demo church on ${template}`);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* The Website's part of a church's export when it leaves (`crosscode export` / uninstall,
|
||||
* WEBSITE-1.0-PLAN §11): `crosscode.church-export/1` with its `website` part, in plain terms and
|
||||
* our own field names (no table names or internal ids; records refer to each other by refs made
|
||||
* for the export). The uploads are copied next to it by the crosscode script (`uploads/`).
|
||||
*
|
||||
* The content is the working copy, including changes not yet published, as the admins left it.
|
||||
*/
|
||||
import { churchExportSchema, type ChurchExport, type ExportWebsite, type WebsiteTemplate, WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
|
||||
const iso = (d: Date | null | undefined) => (d ? d.toISOString() : null);
|
||||
const uploadPath = (filename: string) => `uploads/${filename.replace(/[^A-Za-z0-9._/-]/g, '-')}`;
|
||||
const ROLE_NAMES: Record<string, string> = { owner: 'website owner', admin: 'website admin', editor: 'website editor', ministry_leader: 'ministry leader', viewer: 'website viewer' };
|
||||
|
||||
export async function buildExport(ctx: Ctx): Promise<ChurchExport> {
|
||||
const db = ctx.db;
|
||||
const [design, pages, messages, events, versions, media, users] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.message.findMany({ orderBy: { date: 'asc' }, include: { series: true } }),
|
||||
db.simpleEvent.findMany({ orderBy: { startsAt: 'asc' } }),
|
||||
db.siteVersion.findMany({ orderBy: { number: 'asc' } }),
|
||||
db.mediaAsset.findMany({ orderBy: { createdAt: 'asc' } }),
|
||||
db.websiteUser.findMany({ orderBy: { name: 'asc' } }),
|
||||
]);
|
||||
const mediaPath = new Map(media.map((m) => [m.id, uploadPath(m.filename)]));
|
||||
const names = new Map(users.map((u) => [u.id, u.name]));
|
||||
const template: WebsiteTemplate = (WEBSITE_TEMPLATES as readonly string[]).includes(design?.template ?? '') ? (design!.template as WebsiteTemplate) : 'heritage';
|
||||
|
||||
const website: ExportWebsite = {
|
||||
template,
|
||||
firstPublishedAt: iso(versions[0]?.publishedAt),
|
||||
style: Object.fromEntries(Object.entries((design?.style ?? {}) as Record<string, unknown>).filter(([, v]) => typeof v === 'string')) as Record<string, string>,
|
||||
pages: pages.map((p, n) => ({
|
||||
ref: `g${n + 1}`,
|
||||
title: p.title,
|
||||
path: p.kind === 'home' ? '/' : `/${p.slug}`,
|
||||
kind: p.kind,
|
||||
inNavigation: p.inNav,
|
||||
seo: { title: p.seoTitle, description: p.description },
|
||||
sections: p.sections.map((s) => ({ type: s.type, variant: s.variant ?? '', hidden: s.hidden, content: (s.data ?? {}) as Record<string, never> })),
|
||||
})),
|
||||
messages: messages.map((m, n) => ({
|
||||
ref: `m${n + 1}`, title: m.title, date: iso(m.date), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage, notes: m.notes,
|
||||
url: m.mediaUrl, source: m.source === 'youtube_feed' ? 'youtube-feed' as const : 'manual' as const, hidden: m.hidden,
|
||||
})),
|
||||
events: events.map((e, n) => ({
|
||||
ref: `w${n + 1}`, title: e.title, description: e.description, startsAt: iso(e.startsAt), endsAt: iso(e.endsAt), location: e.location,
|
||||
link: e.link, image: e.imageId ? mediaPath.get(e.imageId) ?? null : null, published: e.publishedAt !== null,
|
||||
})),
|
||||
versions: versions.map((v) => ({ number: v.number, publishedAt: iso(v.publishedAt), by: names.get(v.publishedBy) ?? null, note: v.note })),
|
||||
media: media.map((m) => ({ path: uploadPath(m.filename), alt: m.alt || null, caption: null })),
|
||||
};
|
||||
|
||||
return churchExportSchema.parse({
|
||||
schema: 'crosscode.church-export/1',
|
||||
exportedAt: ctx.now().toISOString(),
|
||||
product: 'website',
|
||||
productVersion: appVersion(),
|
||||
church: { name: (await ctx.settings.get('church_name')) || 'Church Website', timezone: ctx.config.timezone },
|
||||
people: users.map((u, n) => ({
|
||||
ref: `p${n + 1}`, name: u.name, email: u.email, phone: null, role: ROLE_NAMES[u.role] ?? u.role, createdAt: iso(u.createdAt),
|
||||
consent: { email: null, whatsapp: null, privacyNoticeAcceptedAt: null },
|
||||
})),
|
||||
events: [], registrations: [], payments: [], checkIns: [], rosters: [],
|
||||
settings: { address: ctx.config.publicUrl },
|
||||
files: media.map((m) => ({ path: uploadPath(m.filename), bytes: m.bytes })),
|
||||
website,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
|
||||
* Events' /api/v2), async handlers, and a same-origin check on everything that changes something.
|
||||
*/
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Known errors carry a status and code; anything else is a 500. */
|
||||
export function sendError(res: Response, e: unknown) {
|
||||
if (e instanceof ApiError) {
|
||||
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
|
||||
}
|
||||
console.error('[api]', e);
|
||||
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
||||
}
|
||||
|
||||
/** A handler whose result is sent as JSON; an error (thrown or rejected) as `{ error }`. */
|
||||
export const handle = (fn: (req: Request, res: Response) => unknown): RequestHandler => (req, res) => {
|
||||
Promise.resolve().then(() => fn(req, res)).then((out) => {
|
||||
if (out !== undefined && !res.headersSent) res.json(out);
|
||||
}).catch((e) => sendError(res, e));
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes only from the site itself: an `Origin` (or `Referer`) on the site's own address, as
|
||||
* Accounts' http.ts. With SameSite=Lax cookies this stops another site posting on someone's behalf.
|
||||
*/
|
||||
export function sameOrigin(publicUrl: string, production: boolean): RequestHandler {
|
||||
const own = new URL(publicUrl).origin;
|
||||
return (req, res, next) => {
|
||||
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
||||
let origin = req.get('origin') ?? null;
|
||||
if (!origin && req.get('referer')) {
|
||||
try {
|
||||
origin = new URL(req.get('referer')!).origin;
|
||||
} catch {
|
||||
origin = null;
|
||||
}
|
||||
}
|
||||
if (origin === own || (!production && origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin))) return next();
|
||||
return res.status(403).json({ error: { code: 'FORBIDDEN', message: 'That request didn\'t come from this site.' } });
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* The Website and the Hub (docs/hub-protocol.md §6, protocol v2, product `website`), as Accounts'
|
||||
* hub/client.ts: register with a `CCW-` licence key (by itself from HUB_LICENCE_KEY on a Hub
|
||||
* install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's
|
||||
* `linkedProducts` (the church's other installs) is cached for Connect, and the Website connects
|
||||
* itself to the church's Accounts once the Hub lists it (links/connect.ts).
|
||||
*
|
||||
* The install id the Hub gives is also this site's OIDC client id at Accounts.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
import { connectAccountsIfListed } from '../links/connect.js';
|
||||
import { keyPair, saveLinkedProducts } from '../links/store.js';
|
||||
import { hubPublicKey, verifyToken } from './licence.js';
|
||||
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
const TIMEOUT_MS = 15000;
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const STARTED_AT = Date.now();
|
||||
/** 5 GB included (ROADMAP-v3 §10); the licence's `limits.storageBytes` says more when steps were bought. */
|
||||
export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3;
|
||||
|
||||
export class HubError extends Error {
|
||||
constructor(message: string, public code: string, public status: number) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
|
||||
const raw = JSON.stringify(body);
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (sign) {
|
||||
const timestamp = ctx.now().toISOString();
|
||||
headers['X-Hub-Install'] = sign.installId;
|
||||
headers['X-Hub-Timestamp'] = timestamp;
|
||||
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
|
||||
}
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
} catch (e) {
|
||||
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function dbUp(ctx: Ctx): Promise<boolean> {
|
||||
try {
|
||||
await ctx.db.$queryRaw`SELECT 1`;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function health(ctx: Ctx) {
|
||||
return {
|
||||
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||
db: await dbUp(ctx),
|
||||
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
|
||||
lastBackupAt: null,
|
||||
disk: null,
|
||||
errorsLast24h: null,
|
||||
pendingMigrations: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Aggregate counts only (hub.websiteStatsSchema): never anyone's details. */
|
||||
export async function stats(ctx: Ctx) {
|
||||
const now = ctx.now();
|
||||
const since = new Date(now.getTime() - 30 * DAY);
|
||||
const [published, drafts, total, last30d, upcomingSimple, imported, editors, media] = await Promise.all([
|
||||
ctx.db.siteVersion.count(),
|
||||
ctx.db.page.count({ where: { archivedAt: null } }),
|
||||
ctx.db.message.count({ where: { hidden: false } }),
|
||||
ctx.db.message.count({ where: { hidden: false, date: { gte: since } } }),
|
||||
ctx.db.simpleEvent.count({ where: { startsAt: { gte: now }, publishedAt: { not: null } } }),
|
||||
ctx.db.importedEvent.count({ where: { startsAt: { gte: now } } }),
|
||||
ctx.db.websiteUser.count({ where: { role: { not: 'viewer' } } }),
|
||||
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
|
||||
]);
|
||||
return {
|
||||
// Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions).
|
||||
pages: { published: published > 0 ? drafts : 0, drafts: published > 0 ? 0 : drafts },
|
||||
messages: { total, last30d },
|
||||
events: { upcomingSimple, imported },
|
||||
editors,
|
||||
storage: { usedBytes: media._sum.bytes ?? 0, includedBytes: INCLUDED_STORAGE_BYTES },
|
||||
};
|
||||
}
|
||||
|
||||
/** Register with a licence key (HUB_LICENCE_KEY). */
|
||||
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
|
||||
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('WEBSITE_URL isn\'t set.', 'NO_SITE_URL', 400);
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
licenceKey: licenceKey.trim().toUpperCase(),
|
||||
product: 'website',
|
||||
install: {
|
||||
name: 'Website',
|
||||
url: ctx.config.publicUrl,
|
||||
adminContact,
|
||||
version: appVersion(),
|
||||
timezone: ctx.config.timezone,
|
||||
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
|
||||
features: {},
|
||||
publicKey: publicKeyPem,
|
||||
},
|
||||
};
|
||||
const check = hub.registerRequestSchema.safeParse(body);
|
||||
if (!check.success) throw new HubError('That doesn\'t look like a Website licence key (CCW-…).', 'INVALID_REQUEST', 400);
|
||||
const data = await post(ctx, '/api/installs/register', check.data);
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: String(data.installId),
|
||||
hub_install_secret: String(data.installSecret),
|
||||
hub_licence: String(data.licence),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
hub_public_key_status: 'matches',
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return claims;
|
||||
}
|
||||
|
||||
/** The heartbeat (every 15 minutes). Skips quietly when not connected. */
|
||||
export async function heartbeat(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
const secret = await ctx.settings.get('hub_install_secret');
|
||||
if (!installId || !secret) return { skipped: 'not connected' };
|
||||
const status = await ctx.settings.get('hub_public_key_status');
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
product: 'website',
|
||||
version: appVersion(),
|
||||
health: await health(ctx),
|
||||
stats: await stats(ctx),
|
||||
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
|
||||
};
|
||||
try {
|
||||
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
await ctx.settings.setMany({
|
||||
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
|
||||
if (err.code === 'INSTALL_NOT_FOUND') {
|
||||
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
|
||||
return { ok: false, reconnect: true };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY. Never throws. */
|
||||
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
|
||||
const key = ctx.config.hubLicenceKey;
|
||||
if (!key) return { connected: false, reason: 'no_key' };
|
||||
for (let i = 1; i <= attempts; i++) {
|
||||
try {
|
||||
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
|
||||
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
|
||||
return { connected: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
|
||||
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
|
||||
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
|
||||
}
|
||||
}
|
||||
return { connected: false, reason: 'unreachable' };
|
||||
}
|
||||
|
||||
/** Heartbeats every 15 minutes until stopped (pg-boss comes with the Website's other jobs). */
|
||||
export function startHeartbeats(ctx: Ctx): () => void {
|
||||
if (!ctx.config.jobsEnabled) return () => {};
|
||||
const timer = setInterval(() => {
|
||||
heartbeat(ctx).catch((e) => console.warn('[hub] Heartbeat failed:', (e as Error).message));
|
||||
}, 15 * 60 * 1000);
|
||||
timer.unref?.();
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
|
||||
* key, as Cross Events does. A lapsed licence never takes the public site down (the Hub is never on the runtime path,
|
||||
* ROADMAP-v3 §1): admins see a banner.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
|
||||
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
|
||||
export function normalisePem(input: string | null | undefined): string | null {
|
||||
const text = String(input || '').replace(/\\n/g, '\n').trim();
|
||||
if (!text) return null;
|
||||
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
|
||||
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
|
||||
}
|
||||
|
||||
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
|
||||
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
export type LicenceClaims = {
|
||||
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
|
||||
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
|
||||
};
|
||||
|
||||
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
|
||||
if (!pem) return null;
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
|
||||
try {
|
||||
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
|
||||
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
|
||||
|
||||
/** The state for verified claims. Pure. */
|
||||
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
|
||||
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
|
||||
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
|
||||
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
|
||||
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
|
||||
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
|
||||
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
|
||||
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
|
||||
return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
}
|
||||
|
||||
export async function licenceStatus(ctx: Ctx) {
|
||||
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
|
||||
const claims = verifyToken(token, hubPublicKey(ctx));
|
||||
const valid = claims && claims.installId === installId ? claims : null;
|
||||
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
|
||||
}
|
||||
|
||||
/** The church's Hub customer id (the same for every product), once the licence says it. */
|
||||
export async function customerId(ctx: Ctx): Promise<string | null> {
|
||||
return (await licenceStatus(ctx)).claims?.customerId ?? null;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering
|
||||
* with the Hub from HUB_LICENCE_KEY, then heartbeats, which also link the site to the church's
|
||||
* Accounts once the Hub lists it. The other jobs (YouTube feed, storage count, sitemap, feed sync)
|
||||
* come with their features (docs/WEBSITE-1.0-PLAN.md §1).
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from './generated/prisma/client.js';
|
||||
import { createApp } from './app.js';
|
||||
import { createCtx } from './context.js';
|
||||
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
|
||||
import { loadConfig } from './lib/config.js';
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig();
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set.');
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
|
||||
const ctx = createCtx(config, db);
|
||||
const app = createApp(ctx);
|
||||
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
|
||||
const stopHeartbeats = startHeartbeats(ctx);
|
||||
|
||||
connectFromEnv(ctx).then((r) => {
|
||||
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
|
||||
}).catch(() => {});
|
||||
|
||||
const stop = async () => {
|
||||
stopHeartbeats();
|
||||
server.close();
|
||||
await db.$disconnect();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
process.on('SIGINT', stop);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('[website] Failed to start:', e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The admin audit log (who changed what, WEBSITE-1.0-PLAN §4). Logging never breaks the
|
||||
* action it records.
|
||||
*/
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export function clientIp(req: Request | undefined): string | null {
|
||||
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
|
||||
}
|
||||
|
||||
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
|
||||
try {
|
||||
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
|
||||
} catch (e) {
|
||||
console.error('[audit]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
|
||||
* tests pass their own with `loadConfig({...})`.
|
||||
*/
|
||||
export type TrustProxy = false | number | string | string[];
|
||||
|
||||
export type Config = {
|
||||
/** The public address, e.g. https://www.hopefamily.co.za (no trailing slash). */
|
||||
publicUrl: string;
|
||||
port: number;
|
||||
/** Signs preview links and cookies, encrypts stored secrets. Generated on the server, never sent anywhere. */
|
||||
secret: string;
|
||||
production: boolean;
|
||||
/** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */
|
||||
trustProxySetting: TrustProxy;
|
||||
hubUrl: string;
|
||||
hubLicenceKey: string | null;
|
||||
hubPublicKey: string | null;
|
||||
/** The church's contact from the Hub: the first person to sign in with this (verified) email becomes the Owner. */
|
||||
hubAdminName: string | null;
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
jobsEnabled: boolean;
|
||||
/** Where uploads go; default backend/uploads. */
|
||||
uploadDir: string | null;
|
||||
/** Local testing only: linked products (Accounts) on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
/** How long an admin stays signed in (days). */
|
||||
sessionDays: number;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
|
||||
/** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */
|
||||
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
|
||||
const raw = (v ?? '').trim();
|
||||
if (raw === '') return production ? 1 : false;
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'true') return 1;
|
||||
if (lower === 'false') return false;
|
||||
if (/^\d+$/.test(raw)) return Number(raw) || false;
|
||||
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
|
||||
}
|
||||
|
||||
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||
const production = env.NODE_ENV === 'production';
|
||||
const secret = env.WEBSITE_SECRET || '';
|
||||
if (production && secret.length < 32) throw new Error('WEBSITE_SECRET must be set (at least 32 characters) in production.');
|
||||
return {
|
||||
publicUrl: String(env.WEBSITE_URL || 'http://localhost:3300').replace(/\/+$/, ''),
|
||||
port: Number(env.PORT || 5300),
|
||||
secret: secret || 'development-only-secret-change-me-0123456789',
|
||||
production,
|
||||
trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production),
|
||||
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
|
||||
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
|
||||
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
|
||||
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
|
||||
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim().toLowerCase() || null,
|
||||
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
uploadDir: env.UPLOAD_DIR?.trim() || null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Secrets at rest (AES-256-GCM, as Accounts' lib/crypto.ts), and tokens. The key comes from
|
||||
* WEBSITE_SECRET; encrypted values start with "enc:".
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const SENTINEL = 'enc:';
|
||||
|
||||
export class Secrets {
|
||||
private readonly key: Buffer;
|
||||
|
||||
constructor(secret: string) {
|
||||
this.key = crypto.scryptSync(secret, 'crosscode-website-aes256gcm-v1', 32);
|
||||
}
|
||||
|
||||
encrypt(plain: string): string {
|
||||
if (plain.startsWith(SENTINEL)) return plain;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
|
||||
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
|
||||
}
|
||||
|
||||
/** Throws if the value was changed or encrypted with another key. */
|
||||
decrypt(value: string): string {
|
||||
if (!value.startsWith(SENTINEL)) return value;
|
||||
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
|
||||
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/** A random token for a cookie (32 bytes, base64url). */
|
||||
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
/** What's stored for a token: only its SHA-256. */
|
||||
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Site settings in `AppSetting` (key → string), as Accounts' lib/settings.ts. Secret ones are
|
||||
* encrypted at rest and never sent to the browser. A short cache keeps pages from reading the
|
||||
* table on every request.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']);
|
||||
|
||||
const TTL_MS = 30_000;
|
||||
|
||||
export class Settings {
|
||||
private cache = new Map<string, { value: string | null; at: number }>();
|
||||
|
||||
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
const hit = this.cache.get(key);
|
||||
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
||||
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
|
||||
let value = row?.value ?? null;
|
||||
if (value !== null && SECRET_SETTINGS.has(key)) {
|
||||
try {
|
||||
value = this.ctx.secrets.decrypt(value);
|
||||
} catch {
|
||||
value = null;
|
||||
}
|
||||
}
|
||||
this.cache.set(key, { value, at: Date.now() });
|
||||
return value;
|
||||
}
|
||||
|
||||
async bool(key: string, fallback: boolean): Promise<boolean> {
|
||||
const v = await this.get(key);
|
||||
return v === null || v === '' ? fallback : v === 'true';
|
||||
}
|
||||
|
||||
async json<T>(key: string, fallback: T): Promise<T> {
|
||||
const v = await this.get(key);
|
||||
if (!v) return fallback;
|
||||
try {
|
||||
return JSON.parse(v) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
|
||||
else {
|
||||
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
|
||||
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
|
||||
}
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
async setMany(values: Record<string, string | null>): Promise<void> {
|
||||
for (const [k, v] of Object.entries(values)) await this.set(k, v);
|
||||
}
|
||||
|
||||
forget(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
|
||||
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
|
||||
* however the process was started (PM2 doesn't set npm_package_version).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
let cached: string | null = null;
|
||||
|
||||
export function appVersion(): string {
|
||||
if (!cached) {
|
||||
try {
|
||||
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
||||
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
|
||||
} catch {
|
||||
cached = '0.0.0';
|
||||
}
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4 and Accounts). The Website links
|
||||
* to the church's **Accounts** (signing in: the link's secret is where the client secret comes
|
||||
* from, and Accounts registers this site as an OIDC client when it accepts) and, for the event
|
||||
* feed, to **Events** and later the **App**.
|
||||
*
|
||||
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in this
|
||||
* site's cached `linkedProducts` (same church), signed with the key the Hub listed for it.
|
||||
*/
|
||||
import {
|
||||
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
|
||||
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
|
||||
} from '@crosscode/contracts';
|
||||
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { callSibling, LinkCallError, siblingUrl } from './http.js';
|
||||
import { keyPair, linkedProducts, listedProduct } from './store.js';
|
||||
|
||||
export class LinkError extends Error {
|
||||
constructor(message: string, public code: string, public status = 400) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The products the Website links to. */
|
||||
const LINKABLE = new Set(['accounts', 'events', 'app']);
|
||||
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||
|
||||
type Actor = { id: string | null; role: string };
|
||||
|
||||
async function self(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
if (!installId) throw new LinkError('The Website isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
|
||||
const { privateKeyPem } = await keyPair(ctx);
|
||||
return { installId, url: ctx.config.publicUrl, privateKeyPem };
|
||||
}
|
||||
|
||||
const party = (s: { installId: string; url: string }) => ({ product: 'website' as const, installId: s.installId, url: s.url });
|
||||
|
||||
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
|
||||
const now = ctx.now();
|
||||
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||
try {
|
||||
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if ((e as { code?: string }).code === 'P2002') return false;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
|
||||
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById, lastSyncError: null };
|
||||
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||
}
|
||||
|
||||
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: Actor | null, req: Request | undefined, by: string) =>
|
||||
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
|
||||
|
||||
/** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */
|
||||
export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const sibling = await listedProduct(ctx, installId);
|
||||
if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||
const me = await self(ctx);
|
||||
const secret = newLinkSecret();
|
||||
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
let reply: unknown;
|
||||
try {
|
||||
reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
|
||||
} catch (e) {
|
||||
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
|
||||
throw e;
|
||||
}
|
||||
const parsed = linkConnectedSchema.safeParse(reply);
|
||||
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
|
||||
const r: LinkConnected = parsed.data;
|
||||
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() }).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
|
||||
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
|
||||
}
|
||||
const link = await saveLink(ctx, sibling, secret, actor.id);
|
||||
await logLink(ctx, 'product_link_connected', link, actor, req, 'website');
|
||||
return link;
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/connect` (a sibling's admin pressed Connect there). */
|
||||
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise<LinkConnected> {
|
||||
const parsed = linkConnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const sibling = await listedProduct(ctx, m.from.installId);
|
||||
if (!sibling || sibling.product !== m.from.product || !LINKABLE.has(sibling.product)) {
|
||||
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
|
||||
}
|
||||
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() });
|
||||
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
const link = await saveLink(ctx, sibling, m.secret, null);
|
||||
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
|
||||
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
}
|
||||
|
||||
/** This site ends a link. The local link goes even if the sibling can't be reached. */
|
||||
export async function disconnectFrom(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId } });
|
||||
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||
let told = false;
|
||||
let problem: string | null = null;
|
||||
try {
|
||||
const me = await self(ctx);
|
||||
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
|
||||
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||
told = true;
|
||||
} catch (e) {
|
||||
problem = (e as Error).message;
|
||||
}
|
||||
await ctx.db.productLink.delete({ where: { installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'website');
|
||||
return { told, problem };
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
|
||||
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise<void> {
|
||||
const parsed = linkDisconnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||
if (!link) return;
|
||||
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
await ctx.db.productLink.delete({ where: { installId: link.installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Website signs in through Accounts, so it connects to the church's Accounts by itself once the
|
||||
* Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat.
|
||||
* Never throws: a failure is tried again at the next heartbeat.
|
||||
*/
|
||||
export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
|
||||
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped';
|
||||
const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts');
|
||||
if (!listed) return 'skipped';
|
||||
try {
|
||||
await connectTo(ctx, listed.installId, { id: null, role: 'system' });
|
||||
return 'connected';
|
||||
} catch (e) {
|
||||
console.warn('[links] Connecting to Accounts failed:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
|
||||
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
|
||||
*/
|
||||
import dns from 'node:dns/promises';
|
||||
import net from 'node:net';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
const TIMEOUT_MS = 15000;
|
||||
const MAX_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export class LinkCallError extends Error {
|
||||
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function isPrivateAddress(ip: string): boolean {
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number) as [number, number];
|
||||
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
const v = ip.toLowerCase();
|
||||
if (v === '::1' || v === '::') return true;
|
||||
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
|
||||
if (mapped) return isPrivateAddress(mapped[1]!);
|
||||
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function siblingUrl(ctx: Ctx, base: string, path: string): Promise<URL> {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
|
||||
} catch {
|
||||
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
|
||||
}
|
||||
const allow = ctx.config.allowPrivateLinks;
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||
if (!allow) {
|
||||
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
|
||||
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: init.method,
|
||||
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
|
||||
body: init.body,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error).message}`, 'UNREACHABLE');
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||
const text = await res.text();
|
||||
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
|
||||
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* The link endpoints siblings call (`crosscode.link/1`): Accounts (or Events) connecting to and
|
||||
* disconnecting from this site. Errors use the link protocol's `{ code, message }`.
|
||||
*/
|
||||
import express from 'express';
|
||||
import { LINK_PATHS } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
|
||||
|
||||
export function linksRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
const json = express.json({ limit: '32kb' });
|
||||
const fail = (res: express.Response, e: unknown) => {
|
||||
if (e instanceof LinkError) return res.status(e.status).json({ code: e.code, message: e.message });
|
||||
console.error('[links]', e);
|
||||
return res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong.' });
|
||||
};
|
||||
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
res.json(await acceptConnect(ctx, req.body, req));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
r.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
await acceptDisconnect(ctx, req.body, req);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
|
||||
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
|
||||
* hub_linked_products.
|
||||
*/
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
type LinkedProduct = hub.LinkedProduct;
|
||||
|
||||
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
|
||||
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
|
||||
const pair = generateEd25519();
|
||||
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
|
||||
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||
}
|
||||
|
||||
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
|
||||
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
|
||||
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
|
||||
}
|
||||
|
||||
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
|
||||
if (!Array.isArray(list)) return;
|
||||
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
|
||||
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
|
||||
}
|
||||
|
||||
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
|
||||
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Everything the public site needs to draw a page (WEBSITE-1.0-PLAN §1): the latest published
|
||||
* snapshot, the church profile from Accounts, the colours made safe, the fonts and corners, and
|
||||
* the messages and events (which publish on their own, so they're read live). Before the first
|
||||
* publish: Coming soon, from the profile alone (§5).
|
||||
*/
|
||||
import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
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 { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
|
||||
export type SiteEvent = {
|
||||
title: string;
|
||||
summary: string | null;
|
||||
startsAt: string;
|
||||
endsAt: string | null;
|
||||
allDay: boolean;
|
||||
location: string | null;
|
||||
image: Image | null;
|
||||
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
|
||||
url: string;
|
||||
from: 'website' | 'events' | 'app';
|
||||
registration: { status: string; priceFromCents: number | null } | null;
|
||||
};
|
||||
|
||||
export type SiteMessage = {
|
||||
slug: string;
|
||||
title: string;
|
||||
date: string;
|
||||
speaker: string | null;
|
||||
series: string | null;
|
||||
passage: string | null;
|
||||
source: 'youtube' | 'spotify';
|
||||
/** For the embed (youtube-nocookie) or the Spotify player, loaded only when clicked. */
|
||||
embedUrl: string | null;
|
||||
url: string;
|
||||
thumbnail: string | null;
|
||||
};
|
||||
|
||||
type Common = {
|
||||
church: Church | null;
|
||||
palette: Palette;
|
||||
/** The shared brand style, else what the template suggests (§3). */
|
||||
style: { fontPairing: string; corners: string };
|
||||
};
|
||||
|
||||
export type SiteContent =
|
||||
| (Common & { mode: 'coming-soon'; template: WebsiteTemplate; comingSoonText: string })
|
||||
| (Common & {
|
||||
mode: 'published';
|
||||
version: number;
|
||||
/** Without its `source` (the working copy's rows): visitors never get internal ids or hidden sections. */
|
||||
snapshot: Omit<Snapshot, 'source'>;
|
||||
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
|
||||
transparentHeader: Record<string, boolean>;
|
||||
messages: SiteMessage[];
|
||||
events: SiteEvent[];
|
||||
});
|
||||
|
||||
const DEFAULT_COLOUR = '#1f4e79';
|
||||
|
||||
function brandFor(church: Church | null, template: WebsiteTemplate) {
|
||||
return {
|
||||
palette: buildPalette(church?.branding.colours.primary ?? DEFAULT_COLOUR, church?.branding.colours.accent ?? null),
|
||||
style: {
|
||||
fontPairing: church?.branding.style?.fontPairing ?? TEMPLATE_FONT_PAIRINGS[template][0],
|
||||
corners: church?.branding.style?.corners ?? TEMPLATE_STYLE[template].suggestedCorners,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
|
||||
export function youtubeId(url: string): string | null {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.hostname === 'youtu.be') return u.pathname.slice(1) || null;
|
||||
if (/(^|\.)youtube(-nocookie)?\.com$/.test(u.hostname)) return u.searchParams.get('v') ?? (/^\/(embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[2] ?? null);
|
||||
} catch {
|
||||
// Not a URL.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** `https://open.spotify.com/episode/abc` → the embed address; null for anything else. */
|
||||
export function spotifyEmbed(url: string): string | null {
|
||||
const m = /^https:\/\/open\.spotify\.com\/(episode|show)\/([A-Za-z0-9]+)/.exec(url);
|
||||
return m ? `https://open.spotify.com/embed/${m[1]}/${m[2]}` : null;
|
||||
}
|
||||
|
||||
async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
|
||||
const rows = await ctx.db.message.findMany({ where: { hidden: false, publishedAt: { not: null } }, orderBy: { date: 'desc' }, take: 24, include: { series: true } });
|
||||
return rows.map((m) => {
|
||||
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
|
||||
return {
|
||||
slug: m.slug, title: m.title, date: m.date.toISOString(), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage,
|
||||
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),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
const now = ctx.now();
|
||||
const [simple, imported, media] = await Promise.all([
|
||||
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, cancelled: false, OR: [{ startsAt: { gte: now } }, { endsAt: { gte: now } }] }, orderBy: { startsAt: 'asc' }, take: 50 }),
|
||||
ctx.db.importedEvent.findMany({ where: { startsAt: { gte: new Date(now.getTime() - 7 * 864e5) } }, orderBy: { startsAt: 'asc' }, take: 50 }),
|
||||
ctx.db.mediaAsset.findMany(),
|
||||
]);
|
||||
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;
|
||||
};
|
||||
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,
|
||||
}));
|
||||
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,
|
||||
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
|
||||
} satisfies SiteEvent];
|
||||
});
|
||||
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
|
||||
}
|
||||
|
||||
/** What visitors see: the latest published version, else Coming soon. */
|
||||
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
|
||||
return contentFrom(ctx, church, published);
|
||||
}
|
||||
|
||||
/** 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)]);
|
||||
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> {
|
||||
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),
|
||||
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
|
||||
};
|
||||
}
|
||||
const { source: _source, ...snapshot } = published.snapshot;
|
||||
const template = snapshot.design.template;
|
||||
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
|
||||
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The site's colours from the church's two (WEBSITE-1.0-PLAN §3, "Colours from the church, made
|
||||
* safe"): tints and shades, the text colour on each, all checked against WCAG AA (4.5:1 for text).
|
||||
* A colour that fails is darkened (or lightened) until it passes, and the admin is told why.
|
||||
*/
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
const AA = 4.5;
|
||||
const WHITE: Rgb = [255, 255, 255];
|
||||
const INK: Rgb = [17, 24, 39];
|
||||
|
||||
export function hexToRgb(hex: string): Rgb {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
const n = parseInt(m ? m[1]! : '1f4e79', 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
|
||||
export const rgbToHex = (c: Rgb) => `#${c.map((x) => Math.round(x).toString(16).padStart(2, '0')).join('')}`;
|
||||
|
||||
/** "31 78 121": for Tailwind's `rgb(var(--brand) / <alpha-value>)`. */
|
||||
export const triple = (c: Rgb) => c.map((x) => Math.round(x)).join(' ');
|
||||
|
||||
function luminance([r, g, b]: Rgb): number {
|
||||
const lin = (v: number) => {
|
||||
const s = v / 255;
|
||||
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
||||
}
|
||||
|
||||
export function contrast(a: Rgb, b: Rgb): number {
|
||||
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number];
|
||||
return (x + 0.05) / (y + 0.05);
|
||||
}
|
||||
|
||||
/** `c` mixed with `to` by `t` (0 = c, 1 = to). */
|
||||
export const mix = (c: Rgb, to: Rgb, t: number): Rgb => [0, 1, 2].map((i) => c[i]! + (to[i]! - c[i]!) * t) as Rgb;
|
||||
|
||||
/** The nearest shade of `c` (towards black) that reaches `ratio` against `against`. */
|
||||
function darkenUntil(c: Rgb, against: Rgb, ratio = AA): Rgb {
|
||||
for (let t = 0; t <= 1; t += 0.02) {
|
||||
const d = mix(c, [0, 0, 0], t);
|
||||
if (contrast(d, against) >= ratio) return d;
|
||||
}
|
||||
return [0, 0, 0];
|
||||
}
|
||||
|
||||
export type Palette = {
|
||||
/** The church's colour as a background (buttons, bands), with `onBrand` text on it. */
|
||||
brand: string;
|
||||
brandDark: string;
|
||||
onBrand: string;
|
||||
/** The church's colour as text or a link on white: darkened when it's too light to read. */
|
||||
brandText: string;
|
||||
/** A soft background in the church's colour (Section colour "Tinted"). */
|
||||
brandTint: string;
|
||||
accent: string;
|
||||
onAccent: string;
|
||||
/** What was changed and why, for the admin (§3: "the admin is told why"). */
|
||||
notes: string[];
|
||||
};
|
||||
|
||||
export function buildPalette(primaryHex: string, accentHex: string | null): Palette {
|
||||
const notes: string[] = [];
|
||||
const primary = hexToRgb(primaryHex);
|
||||
const accent = accentHex ? hexToRgb(accentHex) : mix(primary, WHITE, 0.25);
|
||||
|
||||
// Text on the brand colour: white when it reads, else dark ink; if neither reaches AA, the
|
||||
// background is darkened until white does.
|
||||
let brand = primary;
|
||||
let onBrand = contrast(WHITE, brand) >= AA ? WHITE : contrast(INK, brand) >= AA ? INK : null;
|
||||
if (!onBrand) {
|
||||
brand = darkenUntil(primary, WHITE);
|
||||
onBrand = WHITE;
|
||||
notes.push(`Your main colour ${rgbToHex(primary)} is darkened to ${rgbToHex(brand)} behind text, so the text on buttons and bands can be read.`);
|
||||
}
|
||||
|
||||
const brandTextRgb = contrast(primary, WHITE) >= AA ? primary : darkenUntil(primary, WHITE);
|
||||
if (brandTextRgb !== primary) notes.push(`Links and headings in your main colour use a darker shade (${rgbToHex(brandTextRgb)}), so they can be read on white.`);
|
||||
|
||||
const onAccent = contrast(WHITE, accent) >= AA ? WHITE : INK;
|
||||
if (contrast(onAccent, accent) < AA) notes.push(`Your accent colour ${rgbToHex(accent)} is only used for decoration: text on it would be hard to read.`);
|
||||
|
||||
return {
|
||||
brand: triple(brand),
|
||||
brandDark: triple(mix(brand, [0, 0, 0], 0.2)),
|
||||
onBrand: triple(onBrand),
|
||||
brandText: triple(brandTextRgb),
|
||||
brandTint: triple(mix(primary, WHITE, 0.92)),
|
||||
accent: triple(accent),
|
||||
onAccent: triple(onAccent),
|
||||
notes,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* What an admin fills in for each homepage section (WEBSITE-1.0-PLAN §2: "every section stores its
|
||||
* data, validated with a zod schema per section type"). Never tied to a template: every template
|
||||
* draws every variant from the same data (§3). Lists (ministries, leaders, events, messages) come
|
||||
* from their own tables; the section only holds its heading and intro.
|
||||
*
|
||||
* Images are media ids here; the published snapshot turns them into `{ url, alt }`.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { SectionType } from './variants.js';
|
||||
|
||||
const text = (max: number) => z.string().trim().max(max);
|
||||
const optional = (max: number) => text(max).nullable().default(null);
|
||||
const mediaId = z.string().uuid();
|
||||
/** A link on the site (`/visit`) or elsewhere (https only). */
|
||||
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
|
||||
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
|
||||
|
||||
export const SECTION_SCHEMAS = {
|
||||
hero: z.object({
|
||||
headline: text(120).min(1),
|
||||
subline: optional(300),
|
||||
/** `photo` and `split` use the first; `collage` up to three. */
|
||||
images: z.array(mediaId).max(3).default([]),
|
||||
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
|
||||
videoId: mediaId.nullable().default(null),
|
||||
button,
|
||||
}),
|
||||
serviceTimes: z.object({
|
||||
heading: optional(80),
|
||||
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
|
||||
note: optional(300),
|
||||
}),
|
||||
welcome: z.object({
|
||||
heading: optional(120),
|
||||
/** The mission line, above the introduction in every variant (§3). */
|
||||
mission: optional(200),
|
||||
body: text(4000).default(''),
|
||||
imageId: mediaId.nullable().default(null),
|
||||
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
|
||||
}),
|
||||
ministries: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
team: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
|
||||
latestMessage: z.object({ heading: optional(80) }),
|
||||
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
|
||||
} as const satisfies Record<SectionType, z.ZodType>;
|
||||
|
||||
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
|
||||
|
||||
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
|
||||
export const BLOCK_SCHEMAS = {
|
||||
text: z.object({ heading: optional(120), body: text(20000) }),
|
||||
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
|
||||
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
|
||||
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
|
||||
} as const;
|
||||
|
||||
export type BlockType = keyof typeof BLOCK_SCHEMAS;
|
||||
export const isBlockType = (t: string): t is BlockType => t in BLOCK_SCHEMAS;
|
||||
|
||||
/** A section's or block's data, checked; null when it doesn't fit (it's then left out, never shown broken). */
|
||||
export function parseSectionData(type: string, data: unknown): Record<string, unknown> | null {
|
||||
const schema = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
|
||||
if (!schema) return null;
|
||||
const r = schema.safeParse(data ?? {});
|
||||
return r.success ? (r.data as Record<string, unknown>) : null;
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Published versions (WEBSITE-1.0-PLAN §4): Publish copies the working copy into an immutable
|
||||
* snapshot (`SiteVersion.snapshot`), and visitors always see the latest. The snapshot holds the
|
||||
* site's design and every page with its sections, ministries and leaders, with images already
|
||||
* turned into `{ url, alt }`, so showing the site never reads the working copy.
|
||||
*
|
||||
* Messages and simple events aren't in it: they publish on their own (decision 9) and are read
|
||||
* live (content.ts).
|
||||
*/
|
||||
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';
|
||||
|
||||
export const SNAPSHOT_VERSION = 1;
|
||||
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null };
|
||||
|
||||
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
|
||||
|
||||
export type SnapshotPage = {
|
||||
kind: string;
|
||||
slug: string;
|
||||
/** `/` for home, else `/<slug>`. */
|
||||
path: string;
|
||||
title: string;
|
||||
seoTitle: string | null;
|
||||
description: string | null;
|
||||
navLabel: string;
|
||||
inNav: boolean;
|
||||
image: Image | null;
|
||||
sections: SnapshotSection[];
|
||||
};
|
||||
|
||||
export type Snapshot = {
|
||||
v: typeof SNAPSHOT_VERSION;
|
||||
design: SiteDesign;
|
||||
pages: SnapshotPage[];
|
||||
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 }[];
|
||||
/** Every image the sections refer to, by media id. */
|
||||
media: Record<string, Image>;
|
||||
/** 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('/')}`;
|
||||
|
||||
/** 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';
|
||||
const base = defaultDesign(template);
|
||||
if (!saved) return base;
|
||||
const variants = { ...base.variants } as Record<SectionType, string>;
|
||||
const v = (saved.variants ?? {}) as Record<string, unknown>;
|
||||
for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
|
||||
const home = Array.isArray(saved.home)
|
||||
? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden }))
|
||||
: base.home;
|
||||
// Every section listed once: any missing one is added at the end, hidden.
|
||||
for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true });
|
||||
const style = { ...base.style, ...Object.fromEntries(Object.entries((saved.style ?? {}) as Record<string, unknown>).filter(([, x]) => typeof x === 'string')) };
|
||||
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
|
||||
}
|
||||
|
||||
/** The working copy's rows, as saved (the source of a snapshot, so a version can be restored, §4). */
|
||||
export type Source = {
|
||||
design: { template: string; variants: unknown; home: unknown; style: unknown } | null;
|
||||
pages: {
|
||||
id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null;
|
||||
inNav: boolean; position: number; imageId: string | null;
|
||||
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
|
||||
}[];
|
||||
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; position: number }[];
|
||||
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; position: number }[];
|
||||
};
|
||||
|
||||
/** Every page, section, ministry and leader that isn't archived, with who last changed it. */
|
||||
export async function readWorkingCopy(ctx: Ctx) {
|
||||
const db = ctx.db;
|
||||
const [design, pages, ministries, leaders] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
]);
|
||||
return { design, pages, ministries, leaders };
|
||||
}
|
||||
|
||||
export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source {
|
||||
return {
|
||||
design: w.design ? { template: w.design.template, variants: w.design.variants, home: w.design.home, style: w.design.style } : null,
|
||||
pages: w.pages.map((p) => ({
|
||||
id: p.id, kind: p.kind, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav,
|
||||
position: p.position, imageId: p.imageId,
|
||||
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
|
||||
})),
|
||||
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position })),
|
||||
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position })),
|
||||
};
|
||||
}
|
||||
|
||||
/** 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 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]));
|
||||
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
|
||||
const used: Record<string, Image> = {};
|
||||
const collect = (data: unknown) => {
|
||||
// Every media id anywhere in a section's data (images, videoId, imageId, photoId).
|
||||
const walk = (x: unknown) => {
|
||||
if (typeof x === 'string' && images.has(x)) used[x] = images.get(x)!;
|
||||
else if (Array.isArray(x)) x.forEach(walk);
|
||||
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
|
||||
};
|
||||
walk(data);
|
||||
};
|
||||
const d = cleanDesign(source.design);
|
||||
const snapshotPages: SnapshotPage[] = source.pages.map((p) => {
|
||||
const sections: SnapshotSection[] = [];
|
||||
if (p.kind === 'home') {
|
||||
// The homepage: the design's order and variants, each section's data from the page.
|
||||
const byType = new Map(p.sections.map((x) => [x.type, x]));
|
||||
for (const entry of d.home) {
|
||||
if (entry.hidden) continue;
|
||||
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
|
||||
}
|
||||
} else {
|
||||
for (const x of p.sections) {
|
||||
if (x.hidden) continue;
|
||||
const data = parseSectionData(x.type, x.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: x.type, variant: x.variant, data });
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: p.kind, slug: p.slug, path: p.kind === 'home' ? '/' : `/${p.slug}`, title: p.title, seoTitle: p.seoTitle, description: p.description,
|
||||
navLabel: p.navLabel || p.title, inNav: p.inNav && p.kind !== 'home', image: image(p.imageId), sections,
|
||||
};
|
||||
});
|
||||
return {
|
||||
v: SNAPSHOT_VERSION,
|
||||
design: d,
|
||||
pages: snapshotPages,
|
||||
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,
|
||||
source,
|
||||
};
|
||||
}
|
||||
|
||||
/** Publish (§4): the whole working copy becomes the next version, at once. */
|
||||
export async function publish(ctx: Ctx, by: { id: string; role: string }, note: string | null = null) {
|
||||
const snapshot = await buildSnapshot(ctx);
|
||||
const last = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true } });
|
||||
const version = await ctx.db.siteVersion.create({
|
||||
data: { number: (last?.number ?? 0) + 1, snapshot: snapshot as never, note, publishedBy: by.id, publishedAt: ctx.now() },
|
||||
});
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'site_published', targetType: 'site_version', targetId: String(version.number), metadata: { note } });
|
||||
return version;
|
||||
}
|
||||
|
||||
/** The latest published snapshot, or null before the first publish (Coming soon). */
|
||||
export async function publishedSnapshot(ctx: Ctx): Promise<{ number: number; publishedAt: Date; snapshot: Snapshot } | null> {
|
||||
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } });
|
||||
if (!latest) return null;
|
||||
const snap = latest.snapshot as unknown as Snapshot;
|
||||
if (!snap || snap.v !== SNAPSHOT_VERSION) return null;
|
||||
return { number: latest.number, publishedAt: latest.publishedAt, snapshot: { ...snap, design: cleanDesign(snap.design as never) } };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* What the public site shows right now: Coming soon until the first publish (§5, decision 3), then
|
||||
* the latest published version. After the first publish there's no going back to Coming soon.
|
||||
*/
|
||||
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export type SiteStatus =
|
||||
| { mode: 'coming-soon' }
|
||||
| { mode: 'published'; version: number; publishedAt: string; template: WebsiteTemplate | null };
|
||||
|
||||
export async function siteStatus(ctx: Ctx): Promise<SiteStatus> {
|
||||
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true, publishedAt: true, snapshot: true } });
|
||||
if (!latest) return { mode: 'coming-soon' };
|
||||
const t = (latest.snapshot as { design?: { template?: unknown } } | null)?.design?.template;
|
||||
const template = (WEBSITE_TEMPLATES as readonly unknown[]).includes(t) ? (t as WebsiteTemplate) : null;
|
||||
return { mode: 'published', version: latest.number, publishedAt: latest.publishedAt.toISOString(), template };
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Section variants per template (docs/WEBSITE-1.0-PLAN.md §3, "Section variants per template",
|
||||
* decision 16, confirmed 2026-11-25).
|
||||
*
|
||||
* Every template draws every variant, so nothing is ever unavailable and a template switch never
|
||||
* needs a fallback. A template only sets which variant each section starts with, which ones it
|
||||
* recommends, its header options, its homepage order and its style defaults.
|
||||
*
|
||||
* The ids are stored on each section (`hero.variant = "photo"`), so **an id never changes or goes
|
||||
* away** once released, like the font pairing ids in `@crosscode/contracts`.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { Corners, WebsiteTemplate } from '@crosscode/contracts';
|
||||
|
||||
/** The homepage section types and their variant ids. */
|
||||
export const SECTION_VARIANTS = {
|
||||
hero: ['photo', 'video', 'collage', 'split', 'text'],
|
||||
serviceTimes: ['panel', 'strip', 'map'],
|
||||
welcome: ['text', 'image-text', 'pastor'],
|
||||
ministries: ['cards', 'list', 'bands'],
|
||||
team: ['faces', 'list', 'featured'],
|
||||
events: ['cards', 'list', 'calendar'],
|
||||
latestMessage: ['video', 'card', 'compact'],
|
||||
invitation: ['banner', 'centred', 'image'],
|
||||
} as const;
|
||||
|
||||
export type SectionType = keyof typeof SECTION_VARIANTS;
|
||||
export type Variant<S extends SectionType = SectionType> = (typeof SECTION_VARIANTS)[S][number];
|
||||
export const SECTION_TYPES = Object.keys(SECTION_VARIANTS) as [SectionType, ...SectionType[]];
|
||||
export const sectionTypeSchema = z.enum(SECTION_TYPES);
|
||||
|
||||
/** Whether `variant` is one of `section`'s ids. */
|
||||
export function isVariant<S extends SectionType>(section: S, variant: string): variant is Variant<S> {
|
||||
return (SECTION_VARIANTS[section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** Per section: the default first, then the other recommended variants. */
|
||||
type Recommendations = { [S in SectionType]: readonly [Variant<S>, ...Variant<S>[]] };
|
||||
|
||||
export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
heritage: {
|
||||
hero: ['photo', 'split', 'text'],
|
||||
serviceTimes: ['panel', 'map'],
|
||||
welcome: ['pastor', 'text'],
|
||||
ministries: ['list', 'cards'],
|
||||
team: ['featured', 'faces'],
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['centred', 'banner'],
|
||||
},
|
||||
bold: {
|
||||
hero: ['video', 'photo', 'split'],
|
||||
serviceTimes: ['strip', 'map'],
|
||||
welcome: ['image-text', 'pastor'],
|
||||
ministries: ['bands', 'cards'],
|
||||
team: ['faces', 'featured'],
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['video', 'card'],
|
||||
invitation: ['image', 'banner'],
|
||||
},
|
||||
community: {
|
||||
hero: ['collage', 'photo', 'split'],
|
||||
serviceTimes: ['map', 'panel'],
|
||||
welcome: ['pastor', 'image-text'],
|
||||
ministries: ['cards', 'bands'],
|
||||
team: ['faces', 'featured'],
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['banner', 'image'],
|
||||
},
|
||||
clean: {
|
||||
hero: ['text', 'split', 'photo'],
|
||||
serviceTimes: ['strip', 'panel'],
|
||||
welcome: ['text', 'image-text'],
|
||||
ministries: ['list', 'cards'],
|
||||
team: ['list', 'faces'],
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['compact', 'card'],
|
||||
invitation: ['centred', 'banner'],
|
||||
},
|
||||
};
|
||||
|
||||
export function defaultVariant<S extends SectionType>(template: WebsiteTemplate, section: S): Variant<S> {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly Variant<S>[])[0]!;
|
||||
}
|
||||
|
||||
export function isRecommended(template: WebsiteTemplate, section: SectionType, variant: string): boolean {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** The "Header" style setting: each template's options, default first. */
|
||||
export const TEMPLATE_HEADERS = {
|
||||
heritage: ['centred', 'centred-top-bar'],
|
||||
bold: ['transparent', 'solid'],
|
||||
community: ['logo-left-button', 'logo-left-tinted'],
|
||||
clean: ['small', 'small-menu'],
|
||||
} as const satisfies Record<WebsiteTemplate, readonly [string, ...string[]]>;
|
||||
|
||||
/**
|
||||
* The transparent header only sits over a photo, video or collage hero; on any other first section
|
||||
* it's drawn solid, so it never puts white text on white.
|
||||
*/
|
||||
export function headerIsTransparent(template: WebsiteTemplate, header: string, heroVariant: Variant<'hero'> | null): boolean {
|
||||
return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant);
|
||||
}
|
||||
|
||||
/** A homepage entry: the section and whether it shows. */
|
||||
export type HomeEntry = { section: SectionType; hidden: boolean };
|
||||
|
||||
const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [
|
||||
...shown.map((section) => ({ section, hidden: false })),
|
||||
...hidden.map((section) => ({ section, hidden: true })),
|
||||
];
|
||||
|
||||
/** The default homepage order (the church can reorder, hide and show). Every section is listed once. */
|
||||
export const TEMPLATE_HOME_ORDER: Record<WebsiteTemplate, HomeEntry[]> = {
|
||||
heritage: order(['hero', 'serviceTimes', 'welcome', 'latestMessage', 'ministries', 'team', 'events', 'invitation']),
|
||||
bold: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'ministries', 'invitation'], ['team']),
|
||||
community: order(['hero', 'welcome', 'serviceTimes', 'ministries', 'team', 'events', 'latestMessage', 'invitation']),
|
||||
clean: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'invitation'], ['ministries', 'team']),
|
||||
};
|
||||
|
||||
/** The Website-only style settings (§3, "Style settings"). Fonts and corners are the church's, shared. */
|
||||
export const SECTION_COLOURS = ['light', 'tinted', 'mixed'] as const;
|
||||
export const SPACINGS = ['airy', 'compact'] as const;
|
||||
export const BUTTONS = ['solid', 'outline', 'pill'] as const;
|
||||
export const IMAGE_TREATMENTS = ['natural', 'mono', 'duotone'] as const;
|
||||
|
||||
export type SiteStyle = {
|
||||
sectionColour: (typeof SECTION_COLOURS)[number];
|
||||
spacing: (typeof SPACINGS)[number];
|
||||
buttons: (typeof BUTTONS)[number];
|
||||
images: (typeof IMAGE_TREATMENTS)[number];
|
||||
header: string;
|
||||
};
|
||||
|
||||
export const TEMPLATE_STYLE: Record<WebsiteTemplate, SiteStyle & { suggestedCorners: Corners }> = {
|
||||
heritage: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'centred', suggestedCorners: 'sharp' },
|
||||
bold: { sectionColour: 'mixed', spacing: 'compact', buttons: 'solid', images: 'natural', header: 'transparent', suggestedCorners: 'sharp' },
|
||||
community: { sectionColour: 'tinted', spacing: 'airy', buttons: 'pill', images: 'natural', header: 'logo-left-button', suggestedCorners: 'round' },
|
||||
clean: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'small', suggestedCorners: 'soft' },
|
||||
};
|
||||
|
||||
const STYLE_KEYS = ['sectionColour', 'spacing', 'buttons', 'images', 'header'] as const;
|
||||
|
||||
/** The site's design: what a template switch changes. Content is never part of it. */
|
||||
export type SiteDesign = {
|
||||
template: WebsiteTemplate;
|
||||
variants: { [S in SectionType]: Variant<S> };
|
||||
home: HomeEntry[];
|
||||
style: SiteStyle;
|
||||
};
|
||||
|
||||
/** A fresh site on `template`: every default. */
|
||||
export function defaultDesign(template: WebsiteTemplate): SiteDesign {
|
||||
const variants = Object.fromEntries(SECTION_TYPES.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
|
||||
const { suggestedCorners: _c, ...style } = TEMPLATE_STYLE[template];
|
||||
return { template, variants, home: TEMPLATE_HOME_ORDER[template].map((e) => ({ ...e })), style };
|
||||
}
|
||||
|
||||
export type DesignChange = { what: string; from: string; to: string };
|
||||
|
||||
const sameOrder = (a: HomeEntry[], b: HomeEntry[]) =>
|
||||
a.length === b.length && a.every((e, i) => e.section === b[i]!.section && e.hidden === b[i]!.hidden);
|
||||
|
||||
/**
|
||||
* Switching template (§3, "Switching template"): anything still on the old template's default
|
||||
* moves to the new template's default; anything the church chose stays. Returns the new design and
|
||||
* what moved, for the Publish screen ("Hero: Collage → Text only, Clean's default").
|
||||
*/
|
||||
export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { design: SiteDesign; changes: DesignChange[] } {
|
||||
if (current.template === to) return { design: current, changes: [] };
|
||||
const from = current.template;
|
||||
const target = defaultDesign(to);
|
||||
const changes: DesignChange[] = [{ what: 'template', from, to }];
|
||||
|
||||
const variants = { ...current.variants } as Record<SectionType, string>;
|
||||
for (const s of SECTION_TYPES) {
|
||||
const next = target.variants[s];
|
||||
if (current.variants[s] === defaultVariant(from, s) && next !== current.variants[s]) {
|
||||
changes.push({ what: `${s}.variant`, from: current.variants[s], to: next });
|
||||
variants[s] = next;
|
||||
}
|
||||
}
|
||||
|
||||
const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]);
|
||||
const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e }));
|
||||
if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` });
|
||||
|
||||
const style = { ...current.style };
|
||||
const oldStyle = TEMPLATE_STYLE[from];
|
||||
for (const k of STYLE_KEYS) {
|
||||
// A header from the old template's options means nothing in the new one, so it always moves.
|
||||
const untouched = current.style[k] === oldStyle[k] || (k === 'header' && !(TEMPLATE_HEADERS[to] as readonly string[]).includes(current.style.header));
|
||||
if (untouched && current.style[k] !== target.style[k]) {
|
||||
changes.push({ what: `style.${k}`, from: current.style[k], to: target.style[k] });
|
||||
(style as Record<string, string>)[k] = target.style[k];
|
||||
}
|
||||
}
|
||||
|
||||
return { design: { template: to, variants: variants as SiteDesign['variants'], home, style }, changes };
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Pending changes, Discard and Restore (WEBSITE-1.0-PLAN §4). The working copy is compared with
|
||||
* the latest published version's `source`, item by item: the site's design, each page (with its
|
||||
* sections), each ministry and each leader.
|
||||
*
|
||||
* changes(ctx) what Publish would put live: added, changed or removed, who and when
|
||||
* discard(ctx, key) one item back to its published state (an added one is archived)
|
||||
* restore(ctx, n) a whole version back into the working copy (then previewed and published
|
||||
* like any other change; nothing is lost)
|
||||
*
|
||||
* Archive instead of delete: a removed page, ministry or leader keeps its row (`archivedAt`).
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { publishedSnapshot, readWorkingCopy, toSource, type Source } from './snapshot.js';
|
||||
|
||||
export type ChangeKind = 'added' | 'changed' | 'removed';
|
||||
export type Change = { key: string; kind: ChangeKind; what: 'design' | 'page' | 'ministry' | 'leader'; label: string; by: string | null; at: string | null };
|
||||
|
||||
type Item = { key: string; what: Change['what']; label: string; value: unknown };
|
||||
|
||||
function items(s: Source | null): Map<string, Item> {
|
||||
const m = new Map<string, Item>();
|
||||
if (!s) return m;
|
||||
if (s.design) m.set('design', { key: 'design', what: 'design', label: 'Template and style', value: s.design });
|
||||
for (const p of s.pages) m.set(`page:${p.id}`, { key: `page:${p.id}`, what: 'page', label: p.title, value: p });
|
||||
for (const x of s.ministries) m.set(`ministry:${x.id}`, { key: `ministry:${x.id}`, what: 'ministry', label: x.name, value: x });
|
||||
for (const x of s.leaders) m.set(`leader:${x.id}`, { key: `leader:${x.id}`, what: 'leader', label: x.name, value: x });
|
||||
return m;
|
||||
}
|
||||
|
||||
/** JSON with sorted keys, so two copies of the same thing compare equal. */
|
||||
function stable(v: unknown): string {
|
||||
if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`;
|
||||
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`;
|
||||
return JSON.stringify(v ?? null);
|
||||
}
|
||||
|
||||
async function publishedSource(ctx: Ctx): Promise<Source | null> {
|
||||
return (await publishedSnapshot(ctx))?.snapshot.source ?? null;
|
||||
}
|
||||
|
||||
export async function changes(ctx: Ctx): Promise<Change[]> {
|
||||
const w = await readWorkingCopy(ctx);
|
||||
const now = items(toSource(w));
|
||||
const then = items(await publishedSource(ctx));
|
||||
const names = new Map((await ctx.db.websiteUser.findMany()).map((u) => [u.id, u.name]));
|
||||
// Who changed it last, and when: the row's own, or (for a page) its latest section's.
|
||||
const who = new Map<string, { by: string | null; at: Date | null }>();
|
||||
if (w.design) who.set('design', { by: w.design.updatedBy, at: w.design.updatedAt });
|
||||
for (const p of w.pages) {
|
||||
const latest = [p, ...p.sections].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0]!;
|
||||
who.set(`page:${p.id}`, { by: latest.updatedBy, at: latest.updatedAt });
|
||||
}
|
||||
for (const x of w.ministries) who.set(`ministry:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
|
||||
for (const x of w.leaders) who.set(`leader:${x.id}`, { by: x.updatedBy, at: x.updatedAt });
|
||||
|
||||
const out: Change[] = [];
|
||||
const meta = (key: string) => {
|
||||
const h = who.get(key);
|
||||
return { by: h?.by ? names.get(h.by) ?? null : null, at: h?.at?.toISOString() ?? null };
|
||||
};
|
||||
for (const [key, item] of now) {
|
||||
const before = then.get(key);
|
||||
if (!before) out.push({ key, kind: 'added', what: item.what, label: item.label, ...meta(key) });
|
||||
else if (stable(before.value) !== stable(item.value)) out.push({ key, kind: 'changed', what: item.what, label: item.label, ...meta(key) });
|
||||
}
|
||||
for (const [key, item] of then) if (!now.has(key)) out.push({ key, kind: 'removed', what: item.what, label: item.label, by: null, at: null });
|
||||
return out;
|
||||
}
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
/** Puts one item of `source` into the working copy as it is there (or archives it when absent). */
|
||||
async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
|
||||
const db = ctx.db;
|
||||
const [what, id] = key.split(':') as [string, string | undefined];
|
||||
const stamp = { updatedBy: by.id };
|
||||
if (what === 'design') {
|
||||
if (!source?.design) throw new ApiError(409, 'NOTHING_PUBLISHED', 'The design has never been published, so there\'s nothing to go back to.');
|
||||
const d = source.design;
|
||||
const data = { template: d.template, variants: d.variants as never, home: d.home as never, style: d.style as never, ...stamp };
|
||||
await db.siteDesign.upsert({ where: { id: 1 }, create: { id: 1, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (!id) throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
|
||||
if (what === 'page') {
|
||||
const p = source?.pages.find((x) => x.id === id);
|
||||
if (!p) {
|
||||
await db.page.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } });
|
||||
return;
|
||||
}
|
||||
// A page that was added since takes the slug: move it aside first.
|
||||
const clash = await db.page.findFirst({ where: { slug: p.slug, NOT: { id } } });
|
||||
if (clash) await db.page.update({ where: { id: clash.id }, data: { slug: `${clash.slug}-${clash.id.slice(0, 6)}` } });
|
||||
const data = { kind: p.kind as never, slug: p.slug, title: p.title, seoTitle: p.seoTitle, description: p.description, navLabel: p.navLabel, inNav: p.inNav, position: p.position, imageId: p.imageId, archivedAt: null, ...stamp };
|
||||
await db.page.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
await db.section.deleteMany({ where: { pageId: id } });
|
||||
for (const x of p.sections) await db.section.create({ data: { id: x.id, pageId: id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data as never, ...stamp } });
|
||||
return;
|
||||
}
|
||||
if (what === 'ministry') {
|
||||
const m = source?.ministries.find((x) => x.id === id);
|
||||
if (!m) return void (await db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position, archivedAt: null, ...stamp };
|
||||
await db.ministry.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (what === 'leader') {
|
||||
const l = source?.leaders.find((x) => x.id === id);
|
||||
if (!l) return void (await db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position, archivedAt: null, ...stamp };
|
||||
await db.leader.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
throw new ApiError(400, 'BAD_KEY', 'That isn\'t a change.');
|
||||
}
|
||||
|
||||
/** Discard (§4): one pending change goes back to its published value. */
|
||||
export async function discard(ctx: Ctx, key: string, by: Who) {
|
||||
const pending = (await changes(ctx)).find((c) => c.key === key);
|
||||
if (!pending) throw new ApiError(404, 'NO_SUCH_CHANGE', 'That change isn\'t pending any more.');
|
||||
await apply(ctx, key, await publishedSource(ctx), by);
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'change_discarded', targetType: pending.what, targetId: key, metadata: { label: pending.label, kind: pending.kind } });
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Restore (§4): version `number` back into the working copy, to preview and publish. */
|
||||
export async function restore(ctx: Ctx, number: number, by: Who) {
|
||||
const v = await ctx.db.siteVersion.findUnique({ where: { number } });
|
||||
const source = (v?.snapshot as { source?: Source } | null)?.source;
|
||||
if (!v || !source) throw new ApiError(404, 'NO_SUCH_VERSION', 'That version can\'t be restored.');
|
||||
const keys = new Set([...items(toSource(await readWorkingCopy(ctx))).keys(), ...items(source).keys()]);
|
||||
for (const key of keys) {
|
||||
if (key === 'design' && !source.design) continue;
|
||||
await apply(ctx, key, source, by);
|
||||
}
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'version_restored', targetType: 'site_version', targetId: String(number) });
|
||||
return { restored: number, pending: (await changes(ctx)).length };
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
import { hashToken } from '../src/lib/crypto.js';
|
||||
import { dimensions, sniff } from '../src/admin/media.js';
|
||||
import { harness, SITE } from './support/harness.js';
|
||||
|
||||
type Role = 'owner' | 'admin' | 'editor' | 'ministry_leader' | 'viewer';
|
||||
|
||||
/** The demo church, and a signed-in admin with `role`. Returns a request helper with their cookie. */
|
||||
async function signedIn(role: Role = 'editor', opts: { ministryId?: string | null } = {}) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-admin-'));
|
||||
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
|
||||
await loadDemo(h.ctx, 'heritage', { uploadDir: dir });
|
||||
const id = `00000000-0000-4000-8000-00000000000${['owner', 'admin', 'editor', 'ministry_leader', 'viewer'].indexOf(role) + 1}`;
|
||||
await h.db.websiteUser.create({ data: { id, name: `Sam the ${role}`, email: `${role}@hope.test`, role, ministryId: opts.ministryId ?? null } });
|
||||
await h.db.session.create({ data: { tokenHash: hashToken(`token-${role}`), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
|
||||
const cookie = `ccw_session=token-${role}`;
|
||||
const as = {
|
||||
get: (p: string) => request(h.app).get(`/api/v1/admin${p}`).set('Cookie', cookie),
|
||||
put: (p: string, body: object) => request(h.app).put(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
|
||||
post: (p: string, body: object = {}) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).send(body),
|
||||
del: (p: string) => request(h.app).delete(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE),
|
||||
upload: (p: string, bytes: Buffer) => request(h.app).post(`/api/v1/admin${p}`).set('Cookie', cookie).set('Origin', SITE).set('Content-Type', 'application/octet-stream').send(bytes),
|
||||
};
|
||||
const pages = (await as.get('/pages')).body as { id: string; kind: string; slug: string }[];
|
||||
return { ...h, as, id, dir, cookie, page: (kind: string) => pages.find((p) => p.kind === kind)!.id };
|
||||
}
|
||||
|
||||
describe('the admin: who may do what (§10)', () => {
|
||||
it('lets a Viewer look but change nothing', async () => {
|
||||
const { as, page } = await signedIn('viewer');
|
||||
assert.equal((await as.get('/overview')).status, 200);
|
||||
assert.equal((await as.put(`/pages/${page('about')}`, { title: 'Us' })).status, 403);
|
||||
assert.equal((await as.post('/publish')).status, 403);
|
||||
});
|
||||
|
||||
it('lets a Ministry leader change their own ministry only, and not publish', async () => {
|
||||
const { as, db } = await signedIn('ministry_leader');
|
||||
const list = (await as.get('/ministries')).body as { id: string; name: string }[];
|
||||
await db.websiteUser.update({ where: { id: '00000000-0000-4000-8000-000000000004' }, data: { ministryId: list[0]!.id } });
|
||||
assert.equal((await as.put(`/ministries/${list[0]!.id}`, { name: 'Kids church', summary: 'Ages 3 to 12' })).status, 200);
|
||||
assert.equal((await as.put(`/ministries/${list[1]!.id}`, { name: 'Youth' })).status, 403);
|
||||
assert.equal((await as.post('/publish')).status, 403);
|
||||
});
|
||||
|
||||
it('refuses a change that didn\'t come from the site itself', async () => {
|
||||
const { app, cookie, page } = await signedIn('editor');
|
||||
const res = await request(app).put(`/api/v1/admin/pages/${page('about')}`).set('Cookie', cookie).set('Origin', 'https://evil.example').send({ title: 'x' });
|
||||
assert.equal(res.status, 403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('editing, publishing, discarding, restoring (§4)', () => {
|
||||
it('lists a change with who made it; Publish puts it live; nothing left to publish', async () => {
|
||||
const { as, page, app } = await signedIn('editor');
|
||||
assert.deepEqual((await as.get('/changes')).body, []);
|
||||
const r = await as.put(`/pages/${page('about')}`, { title: 'Our story' });
|
||||
assert.equal(r.status, 200);
|
||||
const pending = (await as.get('/changes')).body;
|
||||
assert.equal(pending.length, 1);
|
||||
assert.equal(pending[0].kind, 'changed');
|
||||
assert.equal(pending[0].label, 'Our story');
|
||||
assert.equal(pending[0].by, 'Sam the editor');
|
||||
|
||||
// Visitors still see the published title until Publish.
|
||||
const before = (await request(app).get('/api/v1/site/content')).body;
|
||||
assert.equal(before.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'About us');
|
||||
assert.equal(before.snapshot.source, undefined, 'never sent to visitors');
|
||||
|
||||
const pub = await as.post('/publish', { note: 'New page title' });
|
||||
assert.equal(pub.status, 200);
|
||||
assert.equal(pub.body.number, 2);
|
||||
const after = (await request(app).get('/api/v1/site/content')).body;
|
||||
assert.equal(after.snapshot.pages.find((p: { kind: string }) => p.kind === 'about').title, 'Our story');
|
||||
assert.equal((await as.post('/publish')).body.error.code, 'NOTHING_TO_PUBLISH');
|
||||
});
|
||||
|
||||
it('discards one change, back to its published value; an added page is archived', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
await as.put(`/pages/${page('about')}`, { title: 'Changed' });
|
||||
const added = await as.post('/pages', { title: 'Youth camp', slug: 'youth-camp' });
|
||||
assert.equal(added.status, 200);
|
||||
assert.equal((await as.get('/changes')).body.length, 2);
|
||||
|
||||
assert.equal((await as.post('/discard', { key: `page:${page('about')}` })).status, 200);
|
||||
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
|
||||
await as.post('/discard', { key: `page:${added.body.id}` });
|
||||
assert.deepEqual((await as.get('/changes')).body, []);
|
||||
assert.equal((await as.get(`/pages/${added.body.id}`)).status, 404);
|
||||
assert.equal((await as.post('/discard', { key: 'page:nope' })).status, 404);
|
||||
});
|
||||
|
||||
it('restores an older version into the working copy, to preview and publish', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
await as.put(`/pages/${page('about')}`, { title: 'Version two' });
|
||||
await as.post('/publish');
|
||||
await as.del(`/pages/${page('give')}`);
|
||||
await as.post('/publish');
|
||||
const r = await as.post('/versions/1/restore');
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal((await as.get(`/pages/${page('about')}`)).body.title, 'About us');
|
||||
assert.equal((await as.get(`/pages/${page('give')}`)).status, 200, 'the removed page is back');
|
||||
assert.equal(r.body.pending, 2);
|
||||
const versions = (await as.get('/versions')).body;
|
||||
assert.deepEqual(versions.map((v: { number: number }) => v.number), [3, 2, 1]);
|
||||
});
|
||||
|
||||
it('switches template, keeping the church\'s own choices, and says what moved', async () => {
|
||||
const { as } = await signedIn('editor');
|
||||
await as.put('/design', { variants: { team: 'list' } });
|
||||
const r = await as.put('/design', { template: 'bold' });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.design.template, 'bold');
|
||||
assert.equal(r.body.design.variants.team, 'list', 'kept');
|
||||
assert.equal(r.body.design.variants.hero, 'video', 'moved to Bold\'s default');
|
||||
assert.ok(r.body.moved.some((m: { what: string }) => m.what === 'hero.variant'));
|
||||
assert.equal((await as.put('/design', { variants: { hero: 'spinning' } })).status, 400);
|
||||
assert.equal((await as.put('/design', { style: { header: 'centred' } })).status, 400, 'a Heritage header on Bold');
|
||||
});
|
||||
|
||||
it('checks a section\'s data and says which field is wrong', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
const bad = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: '', button: { label: 'Go', href: 'javascript:x' } } });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.ok(bad.body.error.fields.headline);
|
||||
assert.ok(bad.body.error.fields['button.href']);
|
||||
const good = await as.put(`/pages/${page('home')}/home/hero`, { data: { headline: 'Welcome home' } });
|
||||
assert.equal(good.status, 200);
|
||||
});
|
||||
|
||||
it('adds, moves and removes blocks on a page; refuses an address the site uses', async () => {
|
||||
const { as, page } = await signedIn('editor');
|
||||
const id = page('about');
|
||||
const added = (await as.post(`/pages/${id}/blocks`, { type: 'quote' })).body;
|
||||
assert.equal(added.sections.at(-1).type, 'quote');
|
||||
const quote = added.sections.at(-1).id;
|
||||
const moved = (await as.post(`/pages/${id}/blocks/${quote}/move`, { direction: 'up' })).body;
|
||||
assert.equal(moved.sections.at(-2).id, quote);
|
||||
assert.equal((await as.del(`/pages/${id}/blocks/${quote}`)).body.sections.some((s: { id: string }) => s.id === quote), false);
|
||||
assert.equal((await as.post('/pages', { title: 'Admin', slug: 'admin' })).status, 400);
|
||||
assert.equal((await as.post('/pages', { title: 'Visit', slug: 'visit' })).body.error.code, 'SLUG_TAKEN');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the preview (§4)', () => {
|
||||
it('shows the working copy to a signed-in admin, never to anyone else', async () => {
|
||||
const { as, app, cookie, page } = await signedIn('editor');
|
||||
await as.put(`/pages/${page('about')}`, { title: 'Draft title' });
|
||||
assert.equal((await request(app).get('/api/v1/site/preview')).status, 401);
|
||||
const p = await request(app).get('/api/v1/site/preview').set('Cookie', cookie);
|
||||
assert.equal(p.status, 200);
|
||||
assert.equal(p.body.snapshot.pages.find((x: { kind: string }) => x.kind === 'about').title, 'Draft title');
|
||||
assert.equal(p.body.preview.canPublish, true);
|
||||
assert.match(String(p.headers['x-robots-tag']), /noindex/);
|
||||
});
|
||||
|
||||
it('a shared link works signed out for 7 days, until revoked', async () => {
|
||||
const { as, app } = await signedIn('editor');
|
||||
const link = (await as.post('/preview-links')).body;
|
||||
const token = link.url.split('/preview/')[1];
|
||||
const p = await request(app).get('/api/v1/site/preview').set('x-preview-token', token);
|
||||
assert.equal(p.status, 200);
|
||||
assert.equal(p.body.preview.canPublish, false);
|
||||
await as.del(`/preview-links/${link.id}`);
|
||||
assert.equal((await request(app).get('/api/v1/site/preview').set('x-preview-token', token)).status, 401);
|
||||
assert.equal((await as.get('/preview-links')).body[0].active, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploads and storage (§10, decision 12)', () => {
|
||||
const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]), Buffer.from('IHDR'), Buffer.from([0, 0, 2, 128, 0, 0, 1, 224]), Buffer.alloc(40)]);
|
||||
|
||||
it('knows a photo by its bytes, and its size', () => {
|
||||
assert.deepEqual(sniff(png), { ext: 'png', mime: 'image/png' });
|
||||
assert.deepEqual(dimensions(png, { ext: 'png', mime: 'image/png' }), { width: 640, height: 480 });
|
||||
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);
|
||||
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.
|
||||
await db.mediaAsset.create({ data: { filename: 'big.jpg', mime: 'image/jpeg', bytes: 5 * 1024 ** 3 } });
|
||||
const full = await as.upload('/media', png);
|
||||
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,73 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { createCtx, type Db } from '../src/context.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
import { appVersion } from '../src/lib/version.js';
|
||||
|
||||
type Version = { number: number; publishedAt: Date; snapshot: unknown };
|
||||
|
||||
/** Just what the app uses so far: a ping and the latest published version. */
|
||||
function fakeDb(opts: { up?: boolean; versions?: Version[] } = {}): Db {
|
||||
const versions = opts.versions ?? [];
|
||||
return {
|
||||
$queryRaw: async () => {
|
||||
if (opts.up === false) throw new Error('down');
|
||||
return [{ '?column?': 1 }];
|
||||
},
|
||||
siteVersion: {
|
||||
findFirst: async () => [...versions].sort((a, b) => b.number - a.number)[0] ?? null,
|
||||
},
|
||||
} as unknown as Db;
|
||||
}
|
||||
|
||||
const app = (db: Db) => createApp(createCtx(loadConfig({}), db));
|
||||
|
||||
describe('the app', () => {
|
||||
it('answers /api/health with the product and version', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/health');
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body, { status: 'ok', product: 'website', version: appVersion(), db: true });
|
||||
});
|
||||
|
||||
it('says 503 when the database is down', async () => {
|
||||
const res = await request(app(fakeDb({ up: false }))).get('/api/health');
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal(res.body.db, false);
|
||||
});
|
||||
|
||||
it('shows Coming soon until the first publish', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/v1/site/status');
|
||||
assert.deepEqual(res.body, { mode: 'coming-soon' });
|
||||
});
|
||||
|
||||
it('shows the latest published version after it', async () => {
|
||||
const at = new Date('2026-12-01T08:00:00Z');
|
||||
const res = await request(app(fakeDb({ versions: [
|
||||
{ number: 1, publishedAt: new Date('2026-11-30T08:00:00Z'), snapshot: { design: { template: 'heritage' } } },
|
||||
{ number: 2, publishedAt: at, snapshot: { design: { template: 'clean' } } },
|
||||
] }))).get('/api/v1/site/status');
|
||||
assert.deepEqual(res.body, { mode: 'published', version: 2, publishedAt: at.toISOString(), template: 'clean' });
|
||||
});
|
||||
|
||||
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/nothing');
|
||||
assert.equal(res.status, 404);
|
||||
assert.equal(res.body.error.code, 'NOT_FOUND');
|
||||
assert.equal(res.headers['x-robots-tag'], 'noindex');
|
||||
assert.equal(res.headers['x-powered-by'], undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('config', () => {
|
||||
it('refuses production without a secret', () => {
|
||||
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /WEBSITE_SECRET/);
|
||||
});
|
||||
|
||||
it('defaults to the development ports', () => {
|
||||
const c = loadConfig({});
|
||||
assert.equal(c.port, 5300);
|
||||
assert.equal(c.publicUrl, 'http://localhost:3300');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { after, describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import { churchExportSchema, hub, INTERNAL_ID_KEYS, LINK_SCHEMA, linkConnectSchema, type LinkConnected } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import { buildExport } from '../src/export/churchExport.js';
|
||||
import { stats } from '../src/hub/client.js';
|
||||
import { connectAccountsIfListed } from '../src/links/connect.js';
|
||||
import { keyPair, saveLinkedProducts } from '../src/links/store.js';
|
||||
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID } from './support/harness.js';
|
||||
|
||||
const accountsKeys = generateEd25519();
|
||||
const accountsPublic = ed25519PublicToPem(accountsKeys.publicKey);
|
||||
|
||||
/** The church's Accounts, accepting a connect as apps/accounts/backend/src/links/connect.ts does. */
|
||||
async function fakeAccounts(websitePublicKey: () => Promise<string>, opts: { badSignature?: boolean } = {}) {
|
||||
const app = express();
|
||||
const seen: unknown[] = [];
|
||||
app.post('/api/links/v1/connect', express.json(), async (req, res) => {
|
||||
const m = linkConnectSchema.parse(req.body);
|
||||
seen.push(m);
|
||||
if (!verifyLink(m as unknown as Record<string, unknown>, await websitePublicKey()).ok) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
|
||||
const reply = signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connected', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: `http://127.0.0.1:${port}` },
|
||||
to: { installId: m.from.installId }, inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
|
||||
}, opts.badSignature ? generateEd25519().privateKeyPem : accountsKeys.privateKeyPem);
|
||||
return res.json(reply);
|
||||
});
|
||||
const server = http.createServer(app);
|
||||
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
return { url: `http://127.0.0.1:${port}`, seen, close: () => new Promise((r) => server.close(r)) };
|
||||
}
|
||||
|
||||
const closers: (() => Promise<unknown>)[] = [];
|
||||
after(async () => { for (const c of closers) await c(); });
|
||||
|
||||
describe('linking to the church\'s Accounts', () => {
|
||||
it('connects by itself once the Hub lists an Accounts, with a secret both sides keep', async () => {
|
||||
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
|
||||
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
|
||||
closers.push(accounts.close);
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'nothing listed yet');
|
||||
|
||||
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'connected');
|
||||
const link = await h.db.productLink.findUnique({ where: { installId: ACCOUNTS_INSTALL_ID } });
|
||||
assert.equal(link!.product, 'accounts');
|
||||
const sent = accounts.seen[0] as { secret: string; from: { product: string; installId: string } };
|
||||
assert.equal(sent.from.product, 'website');
|
||||
assert.equal(sent.from.installId, INSTALL_ID);
|
||||
assert.equal(h.ctx.secrets.decrypt(String(link!.secret)), sent.secret);
|
||||
assert.notEqual(link!.secret, sent.secret, 'stored encrypted');
|
||||
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'already linked');
|
||||
assert.equal(accounts.seen.length, 1);
|
||||
});
|
||||
|
||||
it('doesn\'t keep a link whose answer isn\'t signed with the key the Hub listed', async () => {
|
||||
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
|
||||
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem, { badSignature: true });
|
||||
closers.push(accounts.close);
|
||||
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
|
||||
assert.equal(await connectAccountsIfListed(h.ctx), 'failed');
|
||||
assert.equal(await h.db.productLink.count(), 0);
|
||||
});
|
||||
|
||||
it('accepts a connect from a listed sibling signed with its key, once', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test', publicKey: accountsPublic }]);
|
||||
const message = () => signLink({
|
||||
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test' },
|
||||
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
|
||||
}, accountsKeys.privateKeyPem);
|
||||
const m = message();
|
||||
const res = await request(h.app).post('/api/links/v1/connect').send(m);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.type, 'link.connected');
|
||||
assert.ok(verifyLink(res.body, (await keyPair(h.ctx)).publicKeyPem).ok);
|
||||
assert.equal(await h.db.productLink.count(), 1);
|
||||
|
||||
assert.equal((await request(h.app).post('/api/links/v1/connect').send(m)).body.code, 'REPLAYED');
|
||||
const forged = { ...message(), signature: message().signature };
|
||||
assert.equal((await request(h.app).post('/api/links/v1/connect').send(forged)).status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the heartbeat and the export', () => {
|
||||
it('reports aggregate counts the Hub accepts', async () => {
|
||||
const h = await harness();
|
||||
await h.db.mediaAsset.create({ data: { filename: 'hero.jpg', mime: 'image/jpeg', bytes: 1200 } });
|
||||
await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
const s = await stats(h.ctx);
|
||||
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
|
||||
assert.equal(s.storage.usedBytes, 1200);
|
||||
assert.deepEqual(s.pages, { published: 0, drafts: 1 });
|
||||
});
|
||||
|
||||
it('exports the content in crosscode.church-export/1, without internal ids', async () => {
|
||||
const h = await harness();
|
||||
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: {}, home: [], style: { spacing: 'airy' } } });
|
||||
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'hero', variant: 'text', data: { headline: 'Welcome home' } } });
|
||||
const img = await h.db.mediaAsset.create({ data: { filename: '2026/hero.jpg', mime: 'image/jpeg', bytes: 1200, alt: 'The hall' } });
|
||||
await h.db.simpleEvent.create({ data: { slug: 'picnic', title: 'Picnic', startsAt: new Date('2026-12-05T08:00:00Z'), imageId: img.id, publishedAt: new Date() } });
|
||||
await h.db.message.create({ data: { slug: 'hope', title: 'Hope', date: new Date('2026-11-22T08:00:00Z'), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abc' } });
|
||||
await h.db.websiteUser.create({ data: { id: '11111111-1111-4111-8111-111111111111', name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
|
||||
await h.db.siteVersion.create({ data: { number: 1, snapshot: {}, publishedBy: '11111111-1111-4111-8111-111111111111', note: 'First' } });
|
||||
|
||||
const data = await buildExport(h.ctx);
|
||||
assert.ok(churchExportSchema.safeParse(data).success);
|
||||
const w = data.website!;
|
||||
assert.equal(w.template, 'clean');
|
||||
assert.equal(w.pages[0]!.path, '/');
|
||||
assert.deepEqual(w.pages[0]!.sections[0], { type: 'hero', variant: 'text', hidden: false, content: { headline: 'Welcome home' } });
|
||||
assert.equal(w.events[0]!.image, 'uploads/2026/hero.jpg');
|
||||
assert.equal(w.messages[0]!.source, 'youtube-feed');
|
||||
assert.deepEqual(w.versions[0], { number: 1, publishedAt: w.versions[0]!.publishedAt, by: 'Sam', note: 'First' });
|
||||
assert.equal(data.people[0]!.role, 'website owner');
|
||||
|
||||
const keys: string[] = [];
|
||||
const walk = (x: unknown) => {
|
||||
if (Array.isArray(x)) x.forEach(walk);
|
||||
else if (x && typeof x === 'object') for (const [k, v] of Object.entries(x)) { keys.push(k); walk(v); }
|
||||
};
|
||||
walk({ ...data, website: { ...w, pages: w.pages.map((p) => ({ ...p, sections: p.sections.map((s) => ({ ...s, content: {} })) })) } });
|
||||
assert.deepEqual(keys.filter((k) => INTERNAL_ID_KEYS.test(k)), []);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { cookieHeader, cookiesFrom, harness, SITE } from './support/harness.js';
|
||||
|
||||
const OWNER = '11111111-1111-4111-8111-111111111111';
|
||||
const OTHER = '22222222-2222-4222-8222-222222222222';
|
||||
|
||||
/** Signs in from `returnTo` through the stand-in Accounts; returns the callback's response and the cookies after it. */
|
||||
async function signIn(h: Awaited<ReturnType<typeof harness>>, returnTo = '/admin/pages?x=1', cookies: Record<string, string> = {}, mfa = false) {
|
||||
const start = await request(h.app).get(`/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? '&mfa=1' : ''}`).set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(start.status, 303);
|
||||
const after = cookiesFrom(start, cookies);
|
||||
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
|
||||
return { start, back, cookies: cookiesFrom(back, after) };
|
||||
}
|
||||
|
||||
describe('signing in to the admin through Accounts', () => {
|
||||
it('sends people to Accounts with the page they were on', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin%2Fpages');
|
||||
assert.equal(res.status, 303);
|
||||
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//);
|
||||
assert.deepEqual(h.fake.started, [{ returnTo: '/admin/pages', requireTwoFactor: false }]);
|
||||
assert.match(String(res.headers['set-cookie']), /ccw_signin=.*Path=\/api\/auth.*HttpOnly/);
|
||||
});
|
||||
|
||||
it('refuses a foreign return address (back to the home page instead)', async () => {
|
||||
const h = await harness();
|
||||
await request(h.app).get('/api/auth/signin?returnTo=https%3A%2F%2Fevil.test%2F');
|
||||
assert.equal(h.fake.started[0]!.returnTo, '/');
|
||||
});
|
||||
|
||||
it('says so when the Website isn\'t linked to Accounts yet', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
|
||||
assert.equal(res.status, 303);
|
||||
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_UNAVAILABLE&returnTo=%2Fadmin`);
|
||||
});
|
||||
|
||||
it('makes the Hub\'s admin email (verified) the first Owner and lands on the page they started from', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, email: 'Pastor@Hope.test' };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.equal(back.headers.location, `${SITE}/admin/pages?x=1`);
|
||||
assert.ok(cookies.ccw_session);
|
||||
assert.match(String(back.headers['set-cookie']), /ccw_session=.*HttpOnly/);
|
||||
|
||||
const me = await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(me.status, 200);
|
||||
assert.equal(me.body.user.role, 'owner');
|
||||
assert.equal(me.body.user.email, 'pastor@hope.test');
|
||||
assert.equal(me.body.mfa, true);
|
||||
const audit = await h.db.auditLog.findMany({ where: { action: 'first_owner_signed_in' } });
|
||||
assert.equal(audit.length, 1);
|
||||
});
|
||||
|
||||
it('never makes a second Owner, nor one from an unverified email', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, email_verified: false };
|
||||
assert.match((await signIn(h)).back.headers.location!, /code=NO_ACCESS/);
|
||||
assert.equal(await h.db.websiteUser.count(), 0);
|
||||
|
||||
h.fake.next = { sub: OWNER };
|
||||
await signIn(h);
|
||||
h.fake.next = { sub: OTHER };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.match(back.headers.location!, /code=NO_ACCESS/);
|
||||
assert.equal(cookies.ccw_session, undefined);
|
||||
assert.equal(await h.db.websiteUser.count(), 1);
|
||||
});
|
||||
|
||||
it('gives someone without a role on the Website no session', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OTHER, email: 'member@hope.test' };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.match(back.headers.location!, /\/auth\/problem\?code=NO_ACCESS/);
|
||||
assert.equal(cookies.ccw_session, undefined);
|
||||
});
|
||||
|
||||
it('asks Accounts again with a second step for an Owner who signed in without one, once', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd'] };
|
||||
const first = await signIn(h, '/admin');
|
||||
assert.equal(first.back.headers.location, `${SITE}/api/auth/signin?mfa=1&returnTo=%2Fadmin`);
|
||||
assert.equal(first.cookies.ccw_session, undefined);
|
||||
|
||||
// Accounts still says no second step: explained, not looped.
|
||||
const second = await signIn(h, '/admin', first.cookies, true);
|
||||
assert.equal(h.fake.started.at(-1)!.requireTwoFactor, true);
|
||||
assert.match(second.back.headers.location!, /code=TWO_FACTOR_NEEDED/);
|
||||
|
||||
// With it: signed in.
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd', 'mfa'] };
|
||||
const third = await signIn(h, '/admin', {}, true);
|
||||
assert.ok(third.cookies.ccw_session);
|
||||
});
|
||||
|
||||
it('lets an Editor in without a second step, and Owners too when the church turned the rule off', async () => {
|
||||
const h = await harness();
|
||||
await h.db.websiteUser.create({ data: { id: OTHER, name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
|
||||
h.fake.next = { sub: OTHER, email: 'ed@hope.test', amr: ['pwd'] };
|
||||
assert.ok((await signIn(h)).cookies.ccw_session);
|
||||
|
||||
await h.ctx.settings.set('two_factor_required_for_admins', 'false');
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd'] };
|
||||
assert.ok((await signIn(h)).cookies.ccw_session);
|
||||
});
|
||||
|
||||
it('keeps the admin API to signed-in people', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).get('/api/v1/admin/me');
|
||||
assert.equal(res.status, 401);
|
||||
assert.equal(res.body.error.code, 'SIGNED_OUT');
|
||||
const me = await request(h.app).get('/api/auth/me').set('Cookie', 'ccw_session=made-up');
|
||||
assert.equal(me.status, 401);
|
||||
});
|
||||
|
||||
it('signs out here, then at Accounts (all the church\'s sites)', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER };
|
||||
const { cookies } = await signIn(h);
|
||||
const out = await request(h.app).post('/api/auth/signout').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(out.status, 303);
|
||||
assert.equal(out.headers.location, `https://accounts.hope.test/api/oidc/session/end?id_token_hint=id-token-for-${OWNER}`);
|
||||
assert.equal(await h.db.session.count(), 0);
|
||||
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
|
||||
});
|
||||
|
||||
it('ends the person\'s sessions when Accounts says they signed out somewhere', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER };
|
||||
const { cookies } = await signIn(h);
|
||||
const res = await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: JSON.stringify({ sub: OWNER, sid: 'abc' }) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
|
||||
assert.equal((await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: 'nonsense' })).status, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Accounts' calls", () => {
|
||||
const call = (type: string, extra: object) => JSON.stringify({ schema: 'crosscode.identity/1', callId: '33333333-3333-4333-8333-333333333333', occurredAt: new Date().toISOString(), sub: OWNER, type, ...extra });
|
||||
|
||||
it('refuses a call Accounts didn\'t sign', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').send(call('user.updated', {}));
|
||||
assert.equal(res.status, 401);
|
||||
});
|
||||
|
||||
it('keeps the admin\'s name and email current, exports them, and removes them when the account goes', async () => {
|
||||
const h = await harness();
|
||||
await h.db.websiteUser.create({ data: { id: OWNER, name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
|
||||
await h.db.session.create({ data: { tokenHash: 'x', userId: OWNER, expiresAt: new Date(Date.now() + 1e9) } });
|
||||
const send = (body: string) => request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').set('x-test-signed', 'yes').send(body);
|
||||
|
||||
const profile = { name: 'Pastor Samuel', email: 'Sam@Hope.test', email_verified: true, phone_number: null, news_consent: { email: false, whatsapp: false } };
|
||||
assert.deepEqual((await send(call('user.updated', { profile }))).body, { schema: 'crosscode.identity/1', ok: true });
|
||||
const u = await h.db.websiteUser.findUnique({ where: { id: OWNER } });
|
||||
assert.equal(u!.name, 'Pastor Samuel');
|
||||
assert.equal(u!.email, 'sam@hope.test');
|
||||
|
||||
const exp = await send(call('user.export', { exportId: '44444444-4444-4444-8444-444444444444' }));
|
||||
assert.equal(exp.body.product, 'website');
|
||||
assert.equal(exp.body.sections[0].records[0].role, 'owner');
|
||||
|
||||
const del = await send(call('user.deleted', {}));
|
||||
assert.equal(del.body.status, 'deleted');
|
||||
assert.equal(await h.db.websiteUser.count(), 0);
|
||||
assert.equal(await h.db.session.count(), 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
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 { defaultDesign } from '../src/site/variants.js';
|
||||
import { harness } from './support/harness.js';
|
||||
|
||||
const rgb = (triple: string) => triple.split(' ').map(Number) as [number, number, number];
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ccw-'));
|
||||
|
||||
describe('colours from the church, made safe (§3)', () => {
|
||||
it('keeps a dark colour as it is, with white text', () => {
|
||||
const p = buildPalette('#1d5c63', '#e0a458');
|
||||
assert.equal(p.brand, '29 92 99');
|
||||
assert.equal(p.onBrand, '255 255 255');
|
||||
assert.deepEqual(p.notes, []);
|
||||
});
|
||||
|
||||
it('darkens a light colour for text on white, and says why', () => {
|
||||
const p = buildPalette('#f5c542', null);
|
||||
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5);
|
||||
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5);
|
||||
assert.ok(p.notes.some((n) => n.includes('darker shade')));
|
||||
});
|
||||
|
||||
it('always gives readable text on the brand colour, whatever the church picks', () => {
|
||||
for (const hex of ['#ff0000', '#00ff00', '#0000ff', '#888888', '#ffffff', '#000000', '#ff8800', '#00aaaa']) {
|
||||
const p = buildPalette(hex, hex);
|
||||
assert.ok(contrast(rgb(p.onBrand), rgb(p.brand)) >= 4.5, hex);
|
||||
assert.ok(contrast(rgb(p.brandText), [255, 255, 255]) >= 4.5, hex);
|
||||
}
|
||||
assert.deepEqual(hexToRgb('nonsense'), [31, 78, 121]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('section data', () => {
|
||||
it('fills defaults and refuses what doesn\'t fit', () => {
|
||||
assert.deepEqual(parseSectionData('latestMessage', {}), { heading: null });
|
||||
assert.equal(parseSectionData('hero', { headline: '' }), null);
|
||||
assert.equal(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: 'javascript:alert(1)' } }), null);
|
||||
assert.ok(parseSectionData('hero', { headline: 'Hi', button: { label: 'Go', href: '/visit' } }));
|
||||
assert.equal(parseSectionData('nothing', {}), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('publishing (§4)', () => {
|
||||
it('makes an unknown template, variant or section safe', () => {
|
||||
const d = cleanDesign({ template: 'fancy', variants: { hero: 'spinning', team: 'list' }, home: [{ section: 'team' }, { section: 'nope' }], style: { spacing: 'compact', bad: 3 } });
|
||||
assert.equal(d.template, 'heritage');
|
||||
assert.equal(d.variants.hero, 'photo');
|
||||
assert.equal(d.variants.team, 'list');
|
||||
assert.equal(d.home[0]!.section, 'team');
|
||||
assert.equal(d.home.length, 8);
|
||||
assert.ok(d.home.slice(1).every((e) => e.hidden));
|
||||
assert.equal(d.style.spacing, 'compact');
|
||||
});
|
||||
|
||||
it('draws the homepage in the design\'s order and variants, leaving out hidden and broken sections', async () => {
|
||||
const h = await harness();
|
||||
const design = defaultDesign('clean');
|
||||
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: design.variants, home: design.home, style: design.style } });
|
||||
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'hero', data: { headline: 'Welcome' } } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'invitation', data: { heading: '' } } });
|
||||
await h.db.section.create({ data: { pageId: home.id, type: 'team', data: {} } });
|
||||
const snap = await buildSnapshot(h.ctx);
|
||||
const types = snap.pages[0]!.sections.map((s) => s.type);
|
||||
assert.deepEqual(types, ['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage'], 'Clean hides Team; the empty invitation is left out');
|
||||
assert.equal(snap.pages[0]!.sections[0]!.variant, 'text');
|
||||
assert.equal(snap.pages[0]!.path, '/');
|
||||
});
|
||||
|
||||
it('numbers versions and keeps every one', async () => {
|
||||
const h = await harness();
|
||||
await publish(h.ctx, { id: 'u1', role: 'owner' }, 'First');
|
||||
const v2 = await publish(h.ctx, { id: 'u1', role: 'owner' });
|
||||
assert.equal(v2.number, 2);
|
||||
assert.equal(await h.db.siteVersion.count(), 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the public site\'s content', () => {
|
||||
it('is Coming soon before the first publish, from the church profile', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.equal(c.mode, 'coming-soon');
|
||||
assert.equal(c.church, null);
|
||||
assert.equal(c.style.fontPairing, 'classic', 'Heritage\'s default pairing');
|
||||
assert.equal(c.style.corners, 'sharp');
|
||||
});
|
||||
|
||||
for (const template of WEBSITE_TEMPLATES) {
|
||||
it(`loads and publishes the demo church on ${template}`, async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const dir = tmp();
|
||||
await loadDemo(h.ctx, template, { uploadDir: dir });
|
||||
const c = await siteContent(h.ctx);
|
||||
assert.equal(c.mode, 'published');
|
||||
if (c.mode !== 'published') return;
|
||||
assert.equal(c.snapshot.design.template, template);
|
||||
assert.equal(c.church?.name, 'Acacia Hill Church');
|
||||
assert.equal(c.snapshot.pages.length, 9);
|
||||
assert.equal(c.snapshot.ministries.length, 4);
|
||||
assert.equal(c.messages.length, 3);
|
||||
assert.equal(c.events.length, 3);
|
||||
assert.ok(c.events[0]!.startsAt < c.events[1]!.startsAt);
|
||||
assert.equal(c.transparentHeader['/'], template === 'bold', 'only Bold\'s header sits over the hero');
|
||||
const hero = c.snapshot.pages[0]!.sections[0]!;
|
||||
assert.equal(hero.type, 'hero');
|
||||
const firstImage = (hero.data.images as string[])[0]!;
|
||||
assert.match(c.snapshot.media[firstImage]!.url, /^\/api\/uploads\/demo\/hero\.svg$/);
|
||||
assert.ok(fs.existsSync(path.join(dir, 'demo', 'hero.svg')));
|
||||
});
|
||||
}
|
||||
|
||||
it('serves the uploads, never a folder or outside it, and the content over HTTP', async () => {
|
||||
const dir = tmp();
|
||||
const h = await harness({ linked: false, env: { UPLOAD_DIR: dir } });
|
||||
await loadDemo(h.ctx, 'community', { uploadDir: dir });
|
||||
const svg = await request(h.app).get('/api/uploads/demo/hero.svg');
|
||||
assert.equal(svg.status, 200);
|
||||
assert.match(String(svg.headers['content-security-policy']), /sandbox/);
|
||||
assert.equal((await request(h.app).get('/api/uploads/demo/')).status, 404);
|
||||
assert.ok([403, 404].includes((await request(h.app).get('/api/uploads/..%2f..%2fpackage.json')).status));
|
||||
assert.equal((await request(h.app).get('/api/uploads/missing.png')).status, 404);
|
||||
const content = await request(h.app).get('/api/v1/site/content');
|
||||
assert.equal(content.body.mode, 'published');
|
||||
assert.equal(content.body.snapshot.design.template, 'community');
|
||||
});
|
||||
});
|
||||
|
||||
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');
|
||||
assert.equal(youtubeId('https://youtu.be/abc123'), 'abc123');
|
||||
assert.equal(youtubeId('https://www.youtube.com/live/xyz'), 'xyz');
|
||||
assert.equal(youtubeId('https://example.com/watch?v=abc'), null);
|
||||
assert.equal(spotifyEmbed('https://open.spotify.com/episode/4rOoJ6Egrf8K2IrywzwOMk?si=1'), 'https://open.spotify.com/embed/episode/4rOoJ6Egrf8K2IrywzwOMk');
|
||||
assert.equal(spotifyEmbed('https://evil.example/episode/x'), null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* The Website's app on an in-memory database, with a stand-in for `@crosscode/auth-client` (the
|
||||
* real one is tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts),
|
||||
* linked to a church's Accounts and registered with the Hub.
|
||||
*/
|
||||
import type { IdentityClaims } from '@crosscode/contracts';
|
||||
import type { AuthClientModule } from '../../src/auth/accounts.js';
|
||||
import { createApp } from '../../src/app.js';
|
||||
import { createCtx, type Ctx, type Db } from '../../src/context.js';
|
||||
import { loadConfig } from '../../src/lib/config.js';
|
||||
import { memoryDb, type MemoryDb } from './memoryDb.js';
|
||||
|
||||
export const SITE = 'https://www.hope.test';
|
||||
export const ACCOUNTS = 'https://accounts.hope.test';
|
||||
export const ADMIN_EMAIL = 'pastor@hope.test';
|
||||
export const INSTALL_ID = '6f0c1d2e-3a4b-4c5d-8e6f-7a8b9c0d1e2f';
|
||||
export const ACCOUNTS_INSTALL_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||
|
||||
/** What the stand-in Accounts answers with at the next callback. */
|
||||
export type FakeAccounts = {
|
||||
next: Partial<IdentityClaims> & { sub: string };
|
||||
started: { returnTo: string; requireTwoFactor: boolean }[];
|
||||
};
|
||||
|
||||
export function claims(over: Partial<IdentityClaims> & { sub: string }): IdentityClaims {
|
||||
return {
|
||||
schema: 'crosscode.identity/1',
|
||||
name: 'Pastor Sam',
|
||||
email: ADMIN_EMAIL,
|
||||
email_verified: true,
|
||||
phone_number: null,
|
||||
news_consent: { email: false, whatsapp: false },
|
||||
amr: ['pwd', 'mfa'],
|
||||
two_factor: 'totp',
|
||||
privacy_notice_version: 1,
|
||||
...over,
|
||||
} as IdentityClaims;
|
||||
}
|
||||
|
||||
function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
|
||||
class SignInError extends Error {
|
||||
constructor(message: string, public code: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
return {
|
||||
SignInError,
|
||||
accountsClient: async () => ({
|
||||
startSignIn: async (returnTo: string, opts: { requireTwoFactor?: boolean } = {}) => {
|
||||
fake.started.push({ returnTo, requireTwoFactor: !!opts.requireTwoFactor });
|
||||
return { url: `${ACCOUNTS}/api/oidc/auth?mfa=${opts.requireTwoFactor ? 1 : 0}`, cookie: Buffer.from(JSON.stringify({ returnTo })).toString('base64url') };
|
||||
},
|
||||
finishSignIn: async (_url: URL, cookie: string | undefined) => {
|
||||
if (!cookie) throw new SignInError('expired', 'NO_PENDING');
|
||||
const { returnTo } = JSON.parse(Buffer.from(cookie, 'base64url').toString()) as { returnTo: string };
|
||||
return { claims: claims(fake.next), returnTo, idToken: `id-token-for-${fake.next.sub}` };
|
||||
},
|
||||
signOutUrl: (idToken?: string) => `${ACCOUNTS}/api/oidc/session/end?id_token_hint=${idToken ?? ''}`,
|
||||
verifyLogoutToken: async (token: string) => {
|
||||
try {
|
||||
return JSON.parse(token) as { sub: string; sid: string | null };
|
||||
} catch {
|
||||
throw new SignInError('bad', 'BAD_TOKEN');
|
||||
}
|
||||
},
|
||||
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
|
||||
if (headers['x-test-signed'] !== 'yes') throw new SignInError('That call isn\'t signed by Accounts.', 'BAD_SIGNATURE');
|
||||
return JSON.parse(raw.toString('utf8'));
|
||||
},
|
||||
}),
|
||||
} as unknown as AuthClientModule;
|
||||
}
|
||||
|
||||
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
|
||||
const db = memoryDb();
|
||||
const fake: FakeAccounts = { next: { sub: '11111111-1111-4111-8111-111111111111' }, started: [] };
|
||||
const config = loadConfig({ WEBSITE_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
|
||||
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake) });
|
||||
await ctx.settings.set('hub_install_id', INSTALL_ID);
|
||||
if (opts.linked !== false) {
|
||||
await db.productLink.create({ data: { installId: ACCOUNTS_INSTALL_ID, product: 'accounts', url: ACCOUNTS, publicKey: 'unused', secret: ctx.secrets.encrypt('link-secret'), connectedAt: new Date() } });
|
||||
}
|
||||
return { db, ctx, fake, app: createApp(ctx) };
|
||||
}
|
||||
|
||||
export type Harness = Awaited<ReturnType<typeof harness>> & { db: MemoryDb; ctx: Ctx };
|
||||
|
||||
/** `name=value` pairs from a response's Set-Cookie, for the next request. */
|
||||
export function cookiesFrom(res: { headers: Record<string, unknown> }, keep: Record<string, string> = {}): Record<string, string> {
|
||||
const out = { ...keep };
|
||||
for (const line of (res.headers['set-cookie'] as string[] | undefined) ?? []) {
|
||||
const [pair, ...attrs] = line.split(';');
|
||||
const i = pair!.indexOf('=');
|
||||
const name = pair!.slice(0, i).trim();
|
||||
const value = pair!.slice(i + 1).trim();
|
||||
const expired = attrs.some((a) => /^\s*expires=Thu, 01 Jan 1970/i.test(a)) || value === '';
|
||||
if (expired) delete out[name];
|
||||
else out[name] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieHeader = (c: Record<string, string>) => Object.entries(c).map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* An in-memory stand-in for the Prisma client (from Accounts' tests/support/memoryDb.ts): every
|
||||
* model the Website uses, with the schema's defaults and unique fields, generic `where` matching
|
||||
* (equality, in / notIn, gt / gte / lt / lte, not, contains, AND / OR), `include` of the relations
|
||||
* below and `aggregate` sums. Enough to run the whole app in tests.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const DEFAULTS: Record<string, () => Row> = {
|
||||
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
messageSeries: () => ({ summary: null, imageId: null }),
|
||||
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
|
||||
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
|
||||
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
|
||||
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
|
||||
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
|
||||
siteVersion: () => ({ note: null }),
|
||||
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
|
||||
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
|
||||
productLink: () => ({ connectedById: null, lastSyncError: null }),
|
||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
|
||||
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'], siteVersion: ['number'], page: ['slug'], message: ['slug', 'externalId'], previewLink: ['tokenHash'] };
|
||||
const HAS_UPDATED_AT = new Set(['siteDesign', 'page', 'section', 'ministry', 'leader', 'message', 'simpleEvent', 'appSetting', 'productLink']);
|
||||
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
||||
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
||||
page: { sections: { model: 'section', many: true, key: 'pageId' } },
|
||||
message: { series: { model: 'messageSeries', many: false, key: 'seriesId' } },
|
||||
};
|
||||
|
||||
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
||||
|
||||
function matchValue(actual: unknown, cond: unknown): boolean {
|
||||
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
||||
const c = cond as Record<string, unknown>;
|
||||
const insensitive = c.mode === 'insensitive';
|
||||
return Object.entries(c).every(([op, x]) => {
|
||||
switch (op) {
|
||||
case 'mode': return true;
|
||||
case 'equals': return v(actual) === v(x);
|
||||
case 'in': return (x as unknown[]).map(v).includes(v(actual));
|
||||
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
|
||||
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
|
||||
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
|
||||
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
|
||||
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
|
||||
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
||||
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
|
||||
default: throw new Error(`memoryDb: no operator ${op}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
return v(actual) === v(cond);
|
||||
}
|
||||
|
||||
export function matches(row: Row, where: Row = {}): boolean {
|
||||
return Object.entries(where ?? {}).every(([k, cond]) => {
|
||||
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
|
||||
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
|
||||
if (k === 'NOT') return !matches(row, cond as Row);
|
||||
return matchValue(row[k], cond);
|
||||
});
|
||||
}
|
||||
|
||||
const clone = <T>(x: T): T => structuredClone(x);
|
||||
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||
|
||||
function order(rows: Row[], orderBy?: Row | Row[]) {
|
||||
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
||||
return [...rows].sort((a, b) => {
|
||||
for (const o of list) {
|
||||
const [k, dir] = Object.entries(o)[0]!;
|
||||
const x = v(a[k]) as number;
|
||||
const y = v(b[k]) as number;
|
||||
const d = x < y ? -1 : x > y ? 1 : 0;
|
||||
if (d) return dir === 'desc' ? -d : d;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function prismaError(code: string, message: string) {
|
||||
return Object.assign(new Error(message), { code });
|
||||
}
|
||||
|
||||
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
const key = KEYS[name] ?? 'id';
|
||||
const table = () => {
|
||||
if (!tables.has(name)) tables.set(name, new Map());
|
||||
return tables.get(name)!;
|
||||
};
|
||||
const findWhere = (where: Row) => {
|
||||
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
||||
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
||||
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
||||
};
|
||||
const checkUnique = (row: Row, except?: unknown) => {
|
||||
for (const u of UNIQUE[name] ?? []) {
|
||||
if (row[u] == null) continue;
|
||||
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
|
||||
}
|
||||
};
|
||||
const api = {
|
||||
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
|
||||
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
||||
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
|
||||
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
|
||||
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
|
||||
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
|
||||
const rows = [...table().values()].filter((x) => matches(x, where));
|
||||
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
|
||||
},
|
||||
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
|
||||
create: async ({ data }: { data: Row }) => {
|
||||
const now = new Date();
|
||||
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
|
||||
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
|
||||
checkUnique(row);
|
||||
table().set(row[key], row);
|
||||
return clone(row);
|
||||
},
|
||||
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
|
||||
checkUnique(next, r[key]);
|
||||
table().set(r[key], next);
|
||||
return clone(next);
|
||||
},
|
||||
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
|
||||
return { count };
|
||||
},
|
||||
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
|
||||
const r = findWhere(where);
|
||||
return r ? api.update({ where, data: update }) : api.create({ data: create });
|
||||
},
|
||||
delete: async ({ where }: { where: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
|
||||
table().delete(r[key]);
|
||||
cascade(name, r[key]);
|
||||
return clone(r);
|
||||
},
|
||||
deleteMany: async ({ where }: { where?: Row } = {}) => {
|
||||
let count = 0;
|
||||
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
|
||||
return { count };
|
||||
},
|
||||
};
|
||||
const cascade = (from: string, id: unknown) => {
|
||||
if (from === 'page') for (const [k, r] of tables.get('section') ?? []) if (r.pageId === id) tables.get('section')!.delete(k);
|
||||
};
|
||||
const withIncludes = (row: Row, include?: Row) => {
|
||||
for (const [rel, on] of Object.entries(include ?? {})) {
|
||||
const spec = RELATIONS[name]?.[rel];
|
||||
if (!on || !spec) continue;
|
||||
const other = [...(tables.get(spec.model)?.values() ?? [])];
|
||||
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
|
||||
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
|
||||
}
|
||||
return row;
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
|
||||
|
||||
export function memoryDb(): MemoryDb {
|
||||
const tables = new Map<string, Map<unknown, Row>>();
|
||||
const models = new Map<string, ReturnType<typeof model>>();
|
||||
return new Proxy({} as MemoryDb, {
|
||||
get(_t, prop: string) {
|
||||
if (prop === 'tables') return tables;
|
||||
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
|
||||
if (prop === '$disconnect') return async () => {};
|
||||
if (prop === 'then') return undefined;
|
||||
if (!models.has(prop)) models.set(prop, model(prop, tables));
|
||||
return models.get(prop);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import {
|
||||
SECTION_TYPES, SECTION_VARIANTS, TEMPLATE_HEADERS, TEMPLATE_HOME_ORDER, TEMPLATE_STYLE, TEMPLATE_VARIANTS,
|
||||
defaultDesign, defaultVariant, headerIsTransparent, isRecommended, isVariant, switchTemplate,
|
||||
} from '../src/site/variants.js';
|
||||
|
||||
describe('section variants (WEBSITE-1.0-PLAN §3, decision 16)', () => {
|
||||
it('has the 26 confirmed variant ids', () => {
|
||||
assert.equal(Object.values(SECTION_VARIANTS).flat().length, 26);
|
||||
assert.deepEqual(SECTION_VARIANTS.hero, ['photo', 'video', 'collage', 'split', 'text']);
|
||||
});
|
||||
|
||||
it('every template recommends only real variants, without repeats, with a default for every section', () => {
|
||||
for (const t of WEBSITE_TEMPLATES) {
|
||||
for (const s of SECTION_TYPES) {
|
||||
const rec = TEMPLATE_VARIANTS[t][s] as readonly string[];
|
||||
assert.ok(rec.length >= 2, `${t}.${s}`);
|
||||
assert.equal(new Set(rec).size, rec.length, `${t}.${s} repeats`);
|
||||
for (const v of rec) assert.ok(isVariant(s, v), `${t}.${s}: ${v}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('has the confirmed defaults', () => {
|
||||
assert.equal(defaultVariant('heritage', 'hero'), 'photo');
|
||||
assert.equal(defaultVariant('bold', 'hero'), 'video');
|
||||
assert.equal(defaultVariant('community', 'hero'), 'collage');
|
||||
assert.equal(defaultVariant('clean', 'hero'), 'text');
|
||||
assert.equal(defaultVariant('clean', 'latestMessage'), 'compact');
|
||||
assert.ok(isRecommended('heritage', 'team', 'faces'));
|
||||
assert.ok(!isRecommended('heritage', 'team', 'list'));
|
||||
});
|
||||
|
||||
it('lists every section once in each homepage order; Bold hides Team, Clean hides Ministries and Team', () => {
|
||||
for (const t of WEBSITE_TEMPLATES) {
|
||||
assert.deepEqual([...TEMPLATE_HOME_ORDER[t].map((e) => e.section)].sort(), [...SECTION_TYPES].sort(), t);
|
||||
}
|
||||
const hidden = (t: keyof typeof TEMPLATE_HOME_ORDER) => TEMPLATE_HOME_ORDER[t].filter((e) => e.hidden).map((e) => e.section);
|
||||
assert.deepEqual(hidden('heritage'), []);
|
||||
assert.deepEqual(hidden('bold'), ['team']);
|
||||
assert.deepEqual(hidden('community'), []);
|
||||
assert.deepEqual(hidden('clean'), ['ministries', 'team']);
|
||||
});
|
||||
|
||||
it("each template's default header is the first of its options", () => {
|
||||
for (const t of WEBSITE_TEMPLATES) assert.equal(TEMPLATE_STYLE[t].header, TEMPLATE_HEADERS[t][0]);
|
||||
});
|
||||
|
||||
it('suggests the confirmed corners', () => {
|
||||
assert.deepEqual(WEBSITE_TEMPLATES.map((t) => TEMPLATE_STYLE[t].suggestedCorners), ['sharp', 'sharp', 'round', 'soft']);
|
||||
});
|
||||
|
||||
it('only makes the header transparent over a photo, video or collage hero', () => {
|
||||
assert.ok(headerIsTransparent('bold', 'transparent', 'video'));
|
||||
assert.ok(!headerIsTransparent('bold', 'transparent', 'text'));
|
||||
assert.ok(!headerIsTransparent('bold', 'transparent', 'split'));
|
||||
assert.ok(!headerIsTransparent('bold', 'solid', 'photo'));
|
||||
assert.ok(!headerIsTransparent('bold', 'transparent', null));
|
||||
});
|
||||
});
|
||||
|
||||
describe('switching template', () => {
|
||||
it('moves an untouched site to every default of the new template', () => {
|
||||
const { design, changes } = switchTemplate(defaultDesign('community'), 'clean');
|
||||
assert.deepEqual(design, defaultDesign('clean'));
|
||||
assert.ok(changes.some((c) => c.what === 'hero.variant' && c.from === 'collage' && c.to === 'text'));
|
||||
assert.ok(changes.some((c) => c.what === 'home'));
|
||||
assert.equal(changes[0]!.what, 'template');
|
||||
});
|
||||
|
||||
it("keeps the church's own choices", () => {
|
||||
const start = defaultDesign('heritage');
|
||||
start.variants.hero = 'video';
|
||||
start.style.buttons = 'pill';
|
||||
start.home = [...start.home].reverse();
|
||||
const { design, changes } = switchTemplate(start, 'clean');
|
||||
assert.equal(design.template, 'clean');
|
||||
assert.equal(design.variants.hero, 'video');
|
||||
assert.equal(design.style.buttons, 'pill');
|
||||
assert.deepEqual(design.home, start.home);
|
||||
assert.equal(design.variants.team, 'list', 'an untouched section still moves');
|
||||
assert.ok(!changes.some((c) => c.what === 'hero.variant' || c.what === 'home' || c.what === 'style.buttons'));
|
||||
});
|
||||
|
||||
it("moves a header the new template doesn't have", () => {
|
||||
const start = defaultDesign('bold');
|
||||
start.style.header = 'solid';
|
||||
const { design } = switchTemplate(start, 'heritage');
|
||||
assert.equal(design.style.header, 'centred');
|
||||
});
|
||||
|
||||
it('changes nothing when the template stays', () => {
|
||||
const d = defaultDesign('bold');
|
||||
assert.deepEqual(switchTemplate(d, 'bold'), { design: d, changes: [] });
|
||||
});
|
||||
|
||||
it('round-trips an untouched site', () => {
|
||||
const there = switchTemplate(defaultDesign('heritage'), 'bold').design;
|
||||
assert.deepEqual(switchTemplate(there, 'heritage').design, defaultDesign('heritage'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
// ES modules throughout, as Accounts (docs/WEBSITE-1.0-PLAN.md §1).
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"lib": ["ES2023"],
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"sourceMap": true,
|
||||
"rootDir": ".",
|
||||
"outDir": "dist",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src", "tests", "scripts", "prisma.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
test-results/
|
||||
playwright-report/
|
||||
.uploads/
|
||||
screens/
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* The admin's flows (WEBSITE-1.0-PLAN §13): edit → preview (click through the site) → publish →
|
||||
* the public site changes; discard one change; a shared preview link works signed out and stops
|
||||
* after revoking; restore an older version; switch template in preview without losing anything.
|
||||
* Runs on the e2e server (e2e/server.ts): the demo church on Heritage, an admin signed in directly.
|
||||
*/
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test, type BrowserContext, type Page } from "@playwright/test";
|
||||
|
||||
const BACKEND = "http://127.0.0.1:5310";
|
||||
|
||||
async function reset(page: Page) {
|
||||
expect((await page.request.post(`${BACKEND}/test/demo?template=heritage`)).ok()).toBeTruthy();
|
||||
}
|
||||
|
||||
async function signIn(context: BrowserContext, role = "editor") {
|
||||
const res = await context.request.post(`${BACKEND}/test/session?role=${role}`);
|
||||
const { cookie } = await res.json();
|
||||
await context.addCookies([{ name: cookie.name, value: cookie.value, url: "http://localhost:3310" }]);
|
||||
}
|
||||
|
||||
async function aboutTitle(page: Page, title: string) {
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: "About us", exact: true }).first().click();
|
||||
// The list page has a Title field too (Add a page): wait for the page's own editor.
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
await page.getByLabel("Title", { exact: true }).fill(title);
|
||||
await page.getByRole("button", { name: "Save details" }).click();
|
||||
await expect(page.getByText("Saved as a draft.")).toBeVisible();
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => reset(page));
|
||||
|
||||
test("edit, preview the whole site, publish: then visitors see it", async ({ page, context, browser }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "Our story");
|
||||
await page.goto("/admin");
|
||||
await expect(page.getByRole("link", { name: "1 change not published" })).toBeVisible();
|
||||
|
||||
// Preview: the real addresses, with the bar; click through to the changed page.
|
||||
await page.getByRole("link", { name: "Preview", exact: true }).click();
|
||||
await expect(page.getByRole("region", { name: "Preview" })).toBeVisible();
|
||||
await page.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Our story" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Our story" })).toBeVisible();
|
||||
|
||||
// Someone else still sees the published site.
|
||||
const visitor = await browser.newPage();
|
||||
await visitor.goto("/about");
|
||||
await expect(visitor.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
await expect(visitor.getByRole("region", { name: "Preview" })).toHaveCount(0);
|
||||
|
||||
await page.getByRole("button", { name: "Publish" }).click();
|
||||
await expect(page).toHaveURL(/\/admin\/publish/);
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
await visitor.goto("/about");
|
||||
await expect(visitor.getByRole("heading", { level: 1, name: "Our story" })).toBeVisible();
|
||||
await visitor.close();
|
||||
});
|
||||
|
||||
test("discard one change", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "Changed my mind");
|
||||
await page.goto("/admin/publish");
|
||||
await expect(page.getByRole("heading", { name: "1 change not published" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Discard" }).click();
|
||||
await expect(page.getByText("Discarded: back to the published version.")).toBeVisible();
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
});
|
||||
|
||||
test("a shared preview link works signed out, and stops when revoked", async ({ page, context, browser }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "For the pastor");
|
||||
await page.goto("/admin/publish");
|
||||
await page.getByRole("button", { name: "Make a preview link" }).click();
|
||||
const url = (await page.locator("code").textContent())!.trim();
|
||||
|
||||
const pastor = await browser.newContext();
|
||||
const p = await pastor.newPage();
|
||||
await p.goto(new URL(url).pathname);
|
||||
await expect(p.getByRole("region", { name: "Preview" })).toBeVisible();
|
||||
await expect(p.getByRole("button", { name: "Publish" })).toHaveCount(0);
|
||||
await p.goto("/about");
|
||||
await expect(p.getByRole("heading", { level: 1, name: "For the pastor" })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Stop it" }).click();
|
||||
await expect(page.getByText("The link stopped working.")).toBeVisible();
|
||||
await p.goto("/about");
|
||||
await expect(p.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
await expect(p.getByRole("region", { name: "Preview" })).toHaveCount(0);
|
||||
await pastor.close();
|
||||
});
|
||||
|
||||
test("restore an older version, then publish it", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await aboutTitle(page, "Version two");
|
||||
await page.goto("/admin/publish");
|
||||
await page.getByRole("button", { name: "Publish all changes" }).click();
|
||||
await expect(page.getByText("Published: visitors see it now.")).toBeVisible();
|
||||
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();
|
||||
await page.goto("/about");
|
||||
await expect(page.getByRole("heading", { level: 1, name: "About us" })).toBeVisible();
|
||||
});
|
||||
|
||||
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 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 expect(page.getByText("Switched to Heritage.")).toBeVisible();
|
||||
await page.goto("/admin/publish");
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
});
|
||||
|
||||
test("signed out, the admin sends people to sign in and back to the same page", async ({ page }) => {
|
||||
const res = await page.request.get("/admin/pages", { maxRedirects: 0 });
|
||||
expect([303, 307, 308]).toContain(res.status());
|
||||
expect(res.headers().location).toContain("/api/auth/signin?returnTo=%2Fadmin%2Fpages");
|
||||
});
|
||||
|
||||
test("a Viewer sees the admin but can't publish", async ({ page, context }) => {
|
||||
await signIn(context, "viewer");
|
||||
await page.goto("/admin/publish");
|
||||
await expect(page.getByText("Nothing waiting to be published")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: /Publish/ })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("the admin's screens are accessible", 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(path);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
|
||||
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(axe.violations.map((v) => `${path}: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"private": true,
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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 fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import express from 'express';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import { createApp } from '../backend/src/app.js';
|
||||
import { createCtx } from '../backend/src/context.js';
|
||||
import { 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 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);
|
||||
await loadDemo(ctx, websiteTemplateSchema.parse(process.env.DEMO_TEMPLATE ?? 'heritage'), { uploadDir: uploads });
|
||||
|
||||
const app = express();
|
||||
app.post('/test/demo', async (req, res) => {
|
||||
const t = websiteTemplateSchema.safeParse(req.query.template);
|
||||
if (!t.success) return res.status(400).json({ error: 'template' });
|
||||
await loadDemo(ctx, t.data, { uploadDir: uploads });
|
||||
return res.json({ ok: true, template: t.data });
|
||||
});
|
||||
app.post('/test/design', express.json(), async (req, res) => {
|
||||
const d = (await db.siteDesign.findUnique({ where: { id: 1 } })) as { variants: object; style: object; home: unknown };
|
||||
await db.siteDesign.update({ where: { id: 1 }, data: {
|
||||
variants: { ...d.variants, ...(req.body.variants ?? {}) },
|
||||
style: { ...d.style, ...(req.body.style ?? {}) },
|
||||
home: req.body.home ?? d.home,
|
||||
} });
|
||||
const v = await publish(ctx, { id: 'e2e', role: 'system' });
|
||||
res.json({ ok: true, version: v.number });
|
||||
});
|
||||
// A signed-in admin without Accounts: the role's user and a session; the spec sets the cookie.
|
||||
app.post('/test/session', async (req, res) => {
|
||||
const role = String(req.query.role ?? 'editor');
|
||||
const id = `00000000-0000-4000-8000-${String(Math.floor(Math.random() * 1e12)).padStart(12, '0')}`;
|
||||
const token = `e2e-${id}`;
|
||||
await db.websiteUser.create({ data: { id, name: `Test ${role}`, email: `${id}@hope.test`, role: role as never } });
|
||||
await db.session.create({ data: { tokenHash: hashToken(token), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
|
||||
res.json({ cookie: { name: 'ccw_session', value: token } });
|
||||
});
|
||||
app.use(createApp(ctx));
|
||||
app.listen(5310, '127.0.0.1', () => console.log('[e2e] Website backend on 5310 with the demo church.'));
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Every template with the demo church (WEBSITE-1.0-PLAN §13): the pages render at phone and desktop
|
||||
* width, axe finds no violations, and the §11 basics are there (title, description, canonical,
|
||||
* one <h1>, JSON-LD that parses). Screenshots go to e2e/screens/ for a look (not compared yet).
|
||||
*/
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
|
||||
const TEMPLATES = ["heritage", "bold", "community", "clean"] as const;
|
||||
const PAGES = ["/", "/visit", "/ministries", "/events", "/messages", "/contact"];
|
||||
|
||||
async function useTemplate(page: Page, template: string) {
|
||||
const res = await page.request.post(`http://127.0.0.1:5310/test/demo?template=${template}`);
|
||||
expect(res.ok()).toBeTruthy();
|
||||
}
|
||||
|
||||
async function seoBasics(page: Page) {
|
||||
await expect(page).toHaveTitle(/.+/);
|
||||
expect(await page.locator('meta[name="description"]').getAttribute("content")).toBeTruthy();
|
||||
expect(await page.locator('link[rel="canonical"]').getAttribute("href")).toBeTruthy();
|
||||
await expect(page.locator("h1")).toHaveCount(1);
|
||||
for (const ld of await page.locator('script[type="application/ld+json"]').allTextContents()) JSON.parse(ld);
|
||||
expect(await page.locator("html").getAttribute("lang")).toBe("en-ZA");
|
||||
}
|
||||
|
||||
for (const template of TEMPLATES) {
|
||||
test.describe(template, () => {
|
||||
test.beforeEach(async ({ page }) => useTemplate(page, template));
|
||||
|
||||
test("its pages: accessible, with the SEO basics", async ({ page }) => {
|
||||
for (const path of PAGES) {
|
||||
const res = await page.goto(path);
|
||||
expect(res?.status(), path).toBe(200);
|
||||
await expect(page.locator("html")).toHaveAttribute("data-template", template);
|
||||
await seoBasics(page);
|
||||
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(axe.violations.map((v) => `${path}: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("screenshots at phone and desktop", async ({ page }) => {
|
||||
for (const [name, size] of [["desktop", { width: 1366, height: 900 }], ["phone", { width: 390, height: 844 }]] as const) {
|
||||
await page.setViewportSize(size);
|
||||
await page.goto("/");
|
||||
// Scroll through, so lazy images load before the full-page shot.
|
||||
await page.evaluate(async () => {
|
||||
for (let y = 0; y < document.body.scrollHeight; y += 600) { window.scrollTo(0, y); await new Promise((r) => setTimeout(r, 60)); }
|
||||
window.scrollTo(0, 0);
|
||||
});
|
||||
// The page's own images (not the map, which loads from OpenStreetMap).
|
||||
await page.waitForFunction(() => Array.from(document.images).every((i) => i.complete), null, { timeout: 30_000 });
|
||||
await page.screenshot({ path: `e2e/screens/${template}-home-${name}.png`, fullPage: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("the home page has the church's JSON-LD; unknown pages are a real 404", async ({ page }) => {
|
||||
await useTemplate(page, "heritage");
|
||||
await page.goto("/");
|
||||
const ld = JSON.parse((await page.locator('script[type="application/ld+json"]').first().textContent())!);
|
||||
expect(ld["@type"]).toBe("Church");
|
||||
expect(ld.name).toBe("Acacia Hill Church");
|
||||
expect((await page.goto("/no-such-page"))?.status()).toBe(404);
|
||||
});
|
||||
|
||||
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");
|
||||
const sitemap = await (await page.request.get("/sitemap.xml")).text();
|
||||
expect(sitemap).toContain("/visit</loc>");
|
||||
expect(sitemap).not.toContain("/admin");
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
// PM2 config template. Each install keeps its own copy as ecosystem.config.cjs (not in git, so
|
||||
// deploys never change it); crosscode creates it from this file the first time with the church's
|
||||
// PM2 names and ports.
|
||||
module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: 'website-backend',
|
||||
cwd: __dirname + '/backend',
|
||||
script: 'dist/index.js',
|
||||
env: { NODE_ENV: 'production' },
|
||||
max_memory_restart: '400M',
|
||||
},
|
||||
{
|
||||
name: 'website-frontend',
|
||||
cwd: __dirname + '/frontend',
|
||||
script: 'npm',
|
||||
args: 'start -- -p 3300',
|
||||
env: { NODE_ENV: 'production' },
|
||||
max_memory_restart: '400M',
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"schema": "crosscode.env-template/1",
|
||||
"product": "website",
|
||||
"files": {
|
||||
"backend/.env": [
|
||||
{ "name": "NODE_ENV", "layer": "generated", "required": true, "description": "production" },
|
||||
{ "name": "PORT", "layer": "install", "from": "{apiPort}", "required": true, "description": "The backend's port (from the Hub's port list)" },
|
||||
{ "name": "DATABASE_URL", "layer": "generated", "required": true, "description": "Made on the server with a new password; never leaves it" },
|
||||
{ "name": "WEBSITE_SECRET", "layer": "generated", "required": true, "description": "Signs preview links and cookies, encrypts stored secrets: never change it" },
|
||||
{ "name": "WEBSITE_URL", "layer": "install", "from": "https://{domain}", "required": true, "description": "The public address (www. or the Cross Code address)" },
|
||||
{ "name": "TRUST_PROXY", "layer": "server", "required": true, "description": "Behind frp: loopback" },
|
||||
{ "name": "APP_TIMEZONE", "layer": "install", "default": "Africa/Johannesburg" },
|
||||
{ "name": "HUB_URL", "layer": "defaults", "default": "https://hub.crosscode.co.za" },
|
||||
{ "name": "HUB_PUBLIC_KEY", "layer": "defaults", "description": "Only for a Hub other than production" },
|
||||
{ "name": "HUB_LICENCE_KEY", "layer": "install", "description": "A Hub install registers by itself with this (CCW-…)" },
|
||||
{ "name": "HUB_ADMIN_NAME", "layer": "install" },
|
||||
{ "name": "HUB_ADMIN_EMAIL", "layer": "install", "description": "The first person to sign in with this address (through Accounts, verified) becomes the Owner" },
|
||||
{ "name": "JOBS_ENABLED", "layer": "defaults", "default": "true" }
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{ "name": "WEBSITE_API_URL", "layer": "install", "from": "http://127.0.0.1:{apiPort}", "required": true, "description": "Where the pages reach the backend on this server" },
|
||||
{ "name": "WEBSITE_CONTENT_CACHE_SECONDS", "layer": "defaults", "default": "30", "description": "How long the public pages keep the published site; Publish clears it at once" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
.next/
|
||||
next-env.d.ts
|
||||
.env*
|
||||
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -0,0 +1,17 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
// Next.js 16's own flat configs, as Accounts. Run with `npm run lint`.
|
||||
export default defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
{
|
||||
rules: {
|
||||
// Uploads are resized into responsive sizes by the backend (WEBSITE-1.0-PLAN §3), and the
|
||||
// logo and message thumbnails come from elsewhere: no Next image server.
|
||||
"@next/next/no-img-element": "off",
|
||||
},
|
||||
},
|
||||
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
|
||||
]);
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
// Everything under /api is the backend (docs/WEBSITE-1.0-PLAN.md §1). On a server nginx sends it
|
||||
// there; in development (and when Next is reached directly) this rewrite does.
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
poweredByHeader: false,
|
||||
transpilePackages: ["@crosscode/ui"],
|
||||
async rewrites() {
|
||||
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
|
||||
},
|
||||
async headers() {
|
||||
// The public site is indexed (ROADMAP-v3 §11); the admin and shared previews never are.
|
||||
const common = [
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
];
|
||||
const noindex = { key: "X-Robots-Tag", value: "noindex, nofollow" };
|
||||
return [
|
||||
{ source: "/:path*", headers: common },
|
||||
{ source: "/admin/:path*", headers: [noindex] },
|
||||
{ source: "/admin", headers: [noindex] },
|
||||
{ source: "/preview/:path*", headers: [noindex] },
|
||||
{ source: "/auth/:path*", headers: [noindex] },
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Church Website: the church's public site in its template, and the admin",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3300",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint src",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"next": "^16.4.6",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "3.4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
/** A list of things the church keeps (ministries, its team): add, edit, remove. Drafts until Publish. */
|
||||
import { useState } from "react";
|
||||
import { api } from "./api";
|
||||
import { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, useAction, useAdmin } from "./ui";
|
||||
|
||||
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string };
|
||||
|
||||
type Row = Record<string, unknown> & { id: string };
|
||||
|
||||
function Editor({ fields, initial, onSave, onCancel, busy, errors }: { fields: ListField[]; initial: Row | Record<string, unknown>; onSave: (v: Record<string, unknown>) => void; onCancel: () => void; busy: boolean; errors: Record<string, string> }) {
|
||||
const [v, setV] = useState<Record<string, unknown>>(initial);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{fields.map((f) => f.kind === "image"
|
||||
? <ImagePicker key={f.key} label={f.label} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id })} />
|
||||
: (
|
||||
<Field key={f.key} label={f.label} hint={f.hint} error={errors[f.key]}>
|
||||
{f.kind === "text"
|
||||
? <input className={inputClass} value={(v[f.key] as string) ?? ""} maxLength={f.max} onChange={(e) => setV({ ...v, [f.key]: e.target.value || null })} />
|
||||
: <textarea className={inputClass} rows={4} value={(v[f.key] as string) ?? ""} maxLength={f.max} onChange={(e) => setV({ ...v, [f.key]: e.target.value || null })} />}
|
||||
</Field>
|
||||
))}
|
||||
<div className="flex gap-2"><Btn kind="primary" busy={busy} onClick={() => onSave(v)}>Save</Btn><Btn onClick={onCancel}>Cancel</Btn></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }: { path: string; fields: ListField[]; nameKey: string; subKey: string; addLabel: string; canAdd: boolean }) {
|
||||
const { data, error, reload } = useAdmin<Row[]>(path);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
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]));
|
||||
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
|
||||
setEditing(null);
|
||||
await reload();
|
||||
}, "Saved as a draft.");
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
<Panel>
|
||||
{data.length === 0 && <p className="text-gray-600">None yet.</p>}
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{data.map((row) => (
|
||||
<li key={row.id} className="py-3">
|
||||
{editing === row.id ? (
|
||||
<Editor fields={fields} initial={row} busy={busy} errors={errors} onCancel={() => setEditing(null)} onSave={(v) => save(row.id, v)} />
|
||||
) : (
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div><p className="font-medium">{String(row[nameKey])}</p>{row[subKey] ? <p className="text-sm text-gray-600">{String(row[subKey])}</p> : null}</div>
|
||||
<div className="flex gap-2">
|
||||
<Btn onClick={() => setEditing(row.id)}>Edit</Btn>
|
||||
{canAdd && <Btn kind="danger" onClick={() => run(async () => { await api(`${path}/${row.id}`, { method: "DELETE" }); await reload(); }, "Removed (until you publish, you can discard this).")}>Remove</Btn>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
{canAdd && (
|
||||
<Panel title={addLabel}>
|
||||
{editing === "new"
|
||||
? <Editor fields={fields} initial={{}} busy={busy} errors={errors} onCancel={() => setEditing(null)} onSave={(v) => save(null, v)} />
|
||||
: <Btn kind="primary" onClick={() => setEditing("new")}>{addLabel}</Btn>}
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
/** The admin's frame: navigation, the pending change count, Preview and Sign out (§4, §10). */
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { ROLE_NAMES } from "./api";
|
||||
import { cx, useAdmin } from "./ui";
|
||||
|
||||
const NAV = [
|
||||
{ href: "/admin", label: "Dashboard" },
|
||||
{ href: "/admin/template", label: "Template and style" },
|
||||
{ href: "/admin/pages", label: "Pages" },
|
||||
{ href: "/admin/ministries", label: "Ministries" },
|
||||
{ href: "/admin/leaders", label: "Leadership" },
|
||||
{ href: "/admin/media", label: "Media library" },
|
||||
{ href: "/admin/publish", label: "Publish and history" },
|
||||
];
|
||||
|
||||
export function AdminShell({ user, children }: { user: { name: string; role: string }; children: React.ReactNode }) {
|
||||
const path = usePathname();
|
||||
const { data } = useAdmin<{ pending: number }>(`/overview?for=${encodeURIComponent(path)}`);
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 font-sans text-gray-900">
|
||||
<header className="border-b border-gray-200 bg-white">
|
||||
<div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-3 px-4 py-3">
|
||||
<Link href="/admin" className="font-semibold">Website admin</Link>
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
{data && data.pending > 0 && <Link href="/admin/publish" className="rounded-full bg-amber-100 px-3 py-1 font-medium text-amber-900">{data.pending} {data.pending === 1 ? "change" : "changes"} not published</Link>}
|
||||
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that sets the preview cookie: a full page load, not a client navigation */}
|
||||
<a href="/preview/start" className="rounded-md border border-gray-300 px-3 py-1.5 font-semibold hover:bg-gray-50">Preview</a>
|
||||
<span className="text-gray-600">{user.name} · {ROLE_NAMES[user.role] ?? user.role}</span>
|
||||
<form method="post" action="/api/auth/signout"><button type="submit" className="text-gray-600 underline-offset-4 hover:underline">Sign out</button></form>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<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) => {
|
||||
const current = n.href === "/admin" ? path === "/admin" : path.startsWith(n.href);
|
||||
return (
|
||||
<li key={n.href}>
|
||||
<Link href={n.href} aria-current={current ? "page" : undefined}
|
||||
className={cx("block whitespace-nowrap rounded-md px-3 py-2 text-sm", current ? "bg-brand text-brand-on" : "text-gray-700 hover:bg-gray-100")}>{n.label}</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</nav>
|
||||
<main>{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
/** The admin API from the browser (same origin: the session cookie goes along, and so does Origin). */
|
||||
export class AdminError extends Error {
|
||||
constructor(message: string, public code: string, public status: number, public fields: Record<string, string> = {}) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function api<T = unknown>(path: string, opts: { method?: string; body?: unknown; raw?: Blob } = {}): Promise<T> {
|
||||
const res = await fetch(`/api/v1/admin${path}`, {
|
||||
method: opts.method ?? (opts.body !== undefined || opts.raw ? "POST" : "GET"),
|
||||
headers: opts.raw ? { "Content-Type": "application/octet-stream" } : opts.body !== undefined ? { "Content-Type": "application/json" } : undefined,
|
||||
body: opts.raw ?? (opts.body !== undefined ? JSON.stringify(opts.body) : undefined),
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
const e = (data as { error?: { message?: string; code?: string; fields?: Record<string, string> } } | null)?.error;
|
||||
// Signed out: off to sign in (a route on the backend), and back to this page.
|
||||
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||
if (res.status === 401) window.location.href = `/api/auth/signin?returnTo=${encodeURIComponent(window.location.pathname)}`;
|
||||
throw new AdminError(e?.message ?? `Something went wrong (${res.status}).`, e?.code ?? "ERROR", res.status, e?.fields ?? {});
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const ROLE_NAMES: Record<string, string> = { owner: "Owner", admin: "Admin", editor: "Editor", ministry_leader: "Ministry leader", viewer: "Viewer" };
|
||||
export const canEdit = (role: string) => ["owner", "admin", "editor"].includes(role);
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* The forms for each homepage section and block, from one description per type (the backend's
|
||||
* zod schemas in src/site/sections.ts check what's saved; field errors come back by path).
|
||||
*/
|
||||
import { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass } from "./ui";
|
||||
|
||||
type Spec =
|
||||
| { key: string; kind: "text" | "textarea"; label: string; hint?: string; max?: number }
|
||||
| { key: string; kind: "number"; label: string; min: number; max: number }
|
||||
| { key: string; kind: "image"; label: string }
|
||||
| { key: string; kind: "images"; label: string; max: number }
|
||||
| { key: string; kind: "button"; label: string }
|
||||
| { key: string; kind: "group"; label: string; fields: Spec[] };
|
||||
|
||||
const heading: Spec = { key: "heading", kind: "text", label: "Heading", max: 120 };
|
||||
const button: Spec = { key: "button", kind: "button", label: "Button" };
|
||||
|
||||
export const SECTION_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
|
||||
hero: { name: "Top of the page (hero)", fields: [
|
||||
{ key: "headline", kind: "text", label: "Headline", max: 120 },
|
||||
{ key: "subline", kind: "textarea", label: "Under the headline", max: 300 },
|
||||
{ key: "images", kind: "images", label: "Photos (the first for Photo and Split; up to three for Collage)", max: 3 },
|
||||
button,
|
||||
] },
|
||||
serviceTimes: { name: "Service times and location", fields: [heading, { key: "note", kind: "textarea", label: "A note for visitors", hint: "The times and address come from your church profile.", max: 300 }] },
|
||||
welcome: { name: "Welcome", fields: [
|
||||
heading,
|
||||
{ key: "mission", kind: "text", label: "Mission (one line)", max: 200 },
|
||||
{ key: "body", kind: "textarea", label: "Introduction", hint: "Leave an empty line between paragraphs.", max: 4000 },
|
||||
{ key: "imageId", kind: "image", label: "Photo (Image and text layout)" },
|
||||
{ key: "pastor", kind: "group", label: "Pastor's photo and quote (With pastor layout)", fields: [
|
||||
{ key: "name", kind: "text", label: "Name", max: 120 }, { key: "role", kind: "text", label: "Role", max: 80 },
|
||||
{ key: "quote", kind: "textarea", label: "Quote", max: 400 }, { key: "photoId", kind: "image", label: "Photo" },
|
||||
] },
|
||||
] },
|
||||
ministries: { name: "Ministries", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
|
||||
team: { name: "Team", fields: [heading, { key: "intro", kind: "textarea", label: "Introduction", max: 400 }] },
|
||||
events: { name: "Upcoming events", fields: [heading, { key: "count", kind: "number", label: "How many to show", min: 2, max: 12 }] },
|
||||
latestMessage: { name: "Latest message", fields: [heading] },
|
||||
invitation: { name: "Invitation", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button, { key: "imageId", kind: "image", label: "Background photo (Image background layout)" }] },
|
||||
};
|
||||
|
||||
export const BLOCK_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
|
||||
text: { name: "Text", fields: [heading, { key: "body", kind: "textarea", label: "Text", hint: "Leave an empty line between paragraphs.", max: 20000 }] },
|
||||
"image-text": { name: "Image and text", fields: [heading, { key: "body", kind: "textarea", label: "Text", max: 4000 }, { key: "imageId", kind: "image", label: "Photo" }, button] },
|
||||
quote: { name: "Quote", fields: [{ key: "quote", kind: "textarea", label: "Quote", max: 600 }, { key: "by", kind: "text", label: "Who said it", max: 120 }] },
|
||||
cta: { name: "Call to action", fields: [heading, { key: "text", kind: "textarea", label: "Text", max: 400 }, button] },
|
||||
};
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
|
||||
export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string }) {
|
||||
const set = (k: string, v: unknown) => onChange({ ...value, [k]: v });
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{fields.map((f) => {
|
||||
const err = errors[`${prefix}${f.key}`];
|
||||
const v = value[f.key];
|
||||
switch (f.kind) {
|
||||
case "text":
|
||||
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><input className={inputClass} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || null)} /></Field>;
|
||||
case "textarea":
|
||||
return <Field key={f.key} label={f.label} hint={f.hint} error={err}><textarea className={inputClass} rows={f.key === "body" ? 6 : 3} value={(v as string) ?? ""} maxLength={f.max} onChange={(e) => set(f.key, e.target.value || (f.key === "body" ? "" : null))} /></Field>;
|
||||
case "number":
|
||||
return <Field key={f.key} label={f.label} error={err}><input type="number" className={`${inputClass} w-24`} min={f.min} max={f.max} value={(v as number) ?? f.min} onChange={(e) => set(f.key, Number(e.target.value))} /></Field>;
|
||||
case "image":
|
||||
return <div key={f.key}><ImagePicker label={f.label} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
|
||||
case "images": {
|
||||
const list = Array.isArray(v) ? (v as string[]) : [];
|
||||
return (
|
||||
<div key={f.key} className="space-y-2">
|
||||
<p className="text-sm font-medium text-gray-800">{f.label}</p>
|
||||
{list.map((id, i) => <ImagePicker key={i} label={`Photo ${i + 1}`} value={id} onChange={(n) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)}
|
||||
{list.length < f.max && <ImagePicker label={`Photo ${list.length + 1}`} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
case "button": {
|
||||
const b = v as { label: string; href: string } | null;
|
||||
return (
|
||||
<fieldset key={f.key} className="rounded border border-gray-200 p-3">
|
||||
<legend className="px-1 text-sm font-medium text-gray-800">{f.label}</legend>
|
||||
{b ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Says" error={errors[`${prefix}${f.key}.label`]}><input className={inputClass} value={b.label} maxLength={60} onChange={(e) => set(f.key, { ...b, label: e.target.value })} /></Field>
|
||||
<Field label="Goes to" hint="A page here (/visit) or https://…" error={errors[`${prefix}${f.key}.href`]}><input className={inputClass} value={b.href} onChange={(e) => set(f.key, { ...b, href: e.target.value })} /></Field>
|
||||
<Btn kind="link" onClick={() => set(f.key, null)}>No button</Btn>
|
||||
</div>
|
||||
) : <Btn onClick={() => set(f.key, { label: "Plan your visit", href: "/visit" })}>Add a button</Btn>}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
case "group": {
|
||||
const g = v as Data | null;
|
||||
return (
|
||||
<fieldset key={f.key} className="rounded border border-gray-200 p-3">
|
||||
<legend className="px-1 text-sm font-medium text-gray-800">{f.label}</legend>
|
||||
{g ? (
|
||||
<>
|
||||
<DataForm fields={f.fields} value={g} onChange={(n) => set(f.key, n)} errors={errors} prefix={`${prefix}${f.key}.`} />
|
||||
<Btn kind="link" className="mt-3" onClick={() => set(f.key, null)}>Remove</Btn>
|
||||
</>
|
||||
) : <Btn onClick={() => set(f.key, { name: "", role: null, quote: null, photoId: null })}>Add</Btn>}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
/** The media library: pick an image, or upload one (with its alt text) and pick it. */
|
||||
import { useRef, useState } from "react";
|
||||
import { api } from "./api";
|
||||
import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui";
|
||||
|
||||
export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number };
|
||||
export type Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number };
|
||||
|
||||
export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`;
|
||||
|
||||
export function StorageMeter({ s }: { s: Storage }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="h-2 w-full overflow-hidden rounded bg-gray-200" role="progressbar" aria-valuenow={s.percent} aria-valuemin={0} aria-valuemax={100} aria-label="Storage used">
|
||||
<div className={cx("h-full", s.percent >= 100 ? "bg-red-600" : s.percent >= 80 ? "bg-amber-500" : "bg-brand")} style={{ width: `${s.percent}%` }} />
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-600">{gb(s.usedBytes)} of {gb(s.limitBytes)} used</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Upload form: a photo and what it shows (alt text is required, §3 "Every image needs alt text"). */
|
||||
export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem) => void; disabled?: boolean }) {
|
||||
const file = useRef<HTMLInputElement>(null);
|
||||
const [alt, setAlt] = useState("");
|
||||
const { busy, message, run } = useAction();
|
||||
const go = () => run(async () => {
|
||||
const f = file.current?.files?.[0];
|
||||
if (!f) throw new Error("Choose a photo first.");
|
||||
if (!alt.trim()) throw new Error("Say what the photo shows (for people who can't see it).");
|
||||
const m = await api<MediaItem & { filename: string }>(`/media?alt=${encodeURIComponent(alt.trim())}`, { raw: f });
|
||||
setAlt("");
|
||||
if (file.current) file.current.value = "";
|
||||
onUploaded(m);
|
||||
}, "Uploaded.");
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Field label="Photo" hint="JPEG, PNG or WebP, up to 15 MB. Landscape photos of people work best for the top of a page.">
|
||||
<input ref={file} type="file" accept="image/jpeg,image/png,image/webp" className="block text-sm" disabled={disabled} />
|
||||
</Field>
|
||||
<Field label="What the photo shows" hint="Read out to people who can't see it, e.g. “Families at the church picnic”.">
|
||||
<input className={inputClass} value={alt} onChange={(e) => setAlt(e.target.value)} maxLength={500} disabled={disabled} />
|
||||
</Field>
|
||||
<Btn kind="primary" onClick={go} busy={busy} disabled={disabled}>Upload</Btn>
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One image field: shows the chosen image, with Choose and Remove. */
|
||||
export function ImagePicker({ value, onChange, label }: { value: string | null; onChange: (id: string | null) => void; label: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null);
|
||||
const chosen = data?.items.find((m) => m.id === value);
|
||||
return (
|
||||
<div>
|
||||
<span className="block text-sm font-medium text-gray-800">{label}</span>
|
||||
<div className="mt-1 flex items-center gap-3">
|
||||
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
|
||||
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-400">No image</span>}
|
||||
</div>
|
||||
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
|
||||
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
|
||||
</div>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label="Choose an image">
|
||||
<div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Choose an image</h2>
|
||||
<Btn onClick={() => setOpen(false)}>Close</Btn>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
|
||||
{data?.items.map((m) => (
|
||||
<button key={m.id} type="button" onClick={() => { onChange(m.id); setOpen(false); }}
|
||||
className={cx("overflow-hidden rounded border-2 text-left", m.id === value ? "border-brand" : "border-transparent hover:border-gray-300")}>
|
||||
<img src={m.url} alt="" className="aspect-[4/3] w-full object-cover" />
|
||||
<span className="block truncate p-1 text-xs text-gray-600">{m.alt || "No description"}</span>
|
||||
</button>
|
||||
))}
|
||||
</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>}
|
||||
<Uploader disabled={data?.storage.full} onUploaded={(m) => { reload(); onChange(m.id); setOpen(false); }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"use client";
|
||||
|
||||
/** The admin's own building blocks: plain, calm, the church's colour for the main action. */
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, AdminError } from "./api";
|
||||
|
||||
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
|
||||
|
||||
export function Title({ children, sub, actions }: { children: React.ReactNode; sub?: React.ReactNode; actions?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-6 flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">{children}</h1>
|
||||
{sub && <p className="mt-1 text-gray-600">{sub}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap gap-2">{actions}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Panel({ children, className, title }: { children: React.ReactNode; className?: string; title?: string }) {
|
||||
return (
|
||||
<section className={cx("rounded-lg border border-gray-200 bg-white p-5 shadow-sm", className)}>
|
||||
{title && <h2 className="mb-4 text-lg font-semibold text-gray-900">{title}</h2>}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type BtnProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { kind?: "primary" | "secondary" | "danger" | "link"; busy?: boolean };
|
||||
|
||||
export function Btn({ kind = "secondary", busy, className, children, disabled, ...rest }: BtnProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
{...rest}
|
||||
disabled={disabled || busy}
|
||||
className={cx(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-50",
|
||||
kind === "primary" && "bg-brand text-brand-on hover:bg-brand-dark",
|
||||
kind === "secondary" && "border border-gray-300 bg-white text-gray-800 hover:bg-gray-50",
|
||||
kind === "danger" && "border border-red-300 bg-white text-red-700 hover:bg-red-50",
|
||||
kind === "link" && "px-0 py-0 text-brand-text underline-offset-4 hover:underline",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{busy ? "Working…" : children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({ label, hint, error, children }: { label: string; hint?: React.ReactNode; error?: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<label className="block">
|
||||
<span className="block text-sm font-medium text-gray-800">{label}</span>
|
||||
<span className="mt-1 block">{children}</span>
|
||||
{hint && !error && <span className="mt-1 block text-xs text-gray-500">{hint}</span>}
|
||||
{error && <span className="mt-1 block text-xs font-medium text-red-700" role="alert">{error}</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export const inputClass = "w-full rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-brand focus:outline-none focus:ring-2 focus:ring-brand/30";
|
||||
|
||||
export function Notice({ tone = "info", children }: { tone?: "info" | "error" | "success" | "warning"; children: React.ReactNode }) {
|
||||
const tones = { info: "border-blue-200 bg-blue-50 text-blue-900", error: "border-red-200 bg-red-50 text-red-900", success: "border-green-200 bg-green-50 text-green-900", warning: "border-amber-200 bg-amber-50 text-amber-900" };
|
||||
return <div role={tone === "error" ? "alert" : "status"} className={cx("rounded-md border px-4 py-3 text-sm", tones[tone])}>{children}</div>;
|
||||
}
|
||||
|
||||
/** Loads `path` from the admin API; `reload` fetches it again. */
|
||||
export function useAdmin<T>(path: string | null) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const load = useCallback(async () => {
|
||||
if (!path) return;
|
||||
try {
|
||||
setData(await api<T>(path));
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
}, [path]);
|
||||
useEffect(() => {
|
||||
// Fetching on mount is this hook's job.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
load();
|
||||
}, [load]);
|
||||
return { data, error, reload: load, setData };
|
||||
}
|
||||
|
||||
/** Runs an action, keeping its busy state, message and field errors. */
|
||||
export function useAction() {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState<{ tone: "error" | "success"; text: string } | null>(null);
|
||||
const [fields, setFields] = useState<Record<string, string>>({});
|
||||
const run = useCallback(async <T,>(fn: () => Promise<T>, success?: string): Promise<T | null> => {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
setFields({});
|
||||
try {
|
||||
const out = await fn();
|
||||
if (success) setMessage({ tone: "success", text: success });
|
||||
return out;
|
||||
} catch (e) {
|
||||
setMessage({ tone: "error", text: (e as Error).message });
|
||||
if (e instanceof AdminError) setFields(e.fields);
|
||||
return null;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, []);
|
||||
return { busy, message, fields, run, setMessage };
|
||||
}
|
||||
|
||||
export function Loading({ error }: { error?: string | null }) {
|
||||
return error ? <Notice tone="error">{error}</Notice> : <p className="text-gray-500">Loading…</p>;
|
||||
}
|
||||
|
||||
export const when = (iso: string | null) => (iso ? new Intl.DateTimeFormat("en-ZA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }).format(new Date(iso)) : "");
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { loadContent } from "@/site/load";
|
||||
import { churchLd, pageMetadata } from "@/site/meta";
|
||||
import { PageView } from "@/site/PageView";
|
||||
import { Shell } from "@/site/Shell";
|
||||
|
||||
type Props = { params: Promise<{ slug: string }> };
|
||||
|
||||
async function find(slug: string) {
|
||||
const c = await loadContent();
|
||||
if (c.mode !== "published") return { c, page: null };
|
||||
return { c, page: c.snapshot.pages.find((p) => p.kind !== "home" && p.slug === slug) ?? null };
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { c, page } = await find((await params).slug);
|
||||
return c.mode === "published" && page ? pageMetadata(c, page) : { robots: { index: false } };
|
||||
}
|
||||
|
||||
export default async function SitePage({ params }: Props) {
|
||||
const { slug } = await params;
|
||||
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;
|
||||
return (
|
||||
<Shell site={c} path={page.path}>
|
||||
{ld && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />}
|
||||
<PageView page={page} site={c} />
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { AdminShell } from "@/admin/Shell";
|
||||
import { loadMe, signInHref } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Every admin page: signed in through the church's Accounts (§10), else off to sign in and back. */
|
||||
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const me = await loadMe();
|
||||
if (!me) {
|
||||
const path = (await headers()).get("x-ccw-path") || "/admin";
|
||||
redirect(signInHref(path.startsWith("/admin") ? path : "/admin"));
|
||||
}
|
||||
return <AdminShell user={me.user}>{children}</AdminShell>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { canEdit } from "@/admin/api";
|
||||
import { ListEditor } from "@/admin/ListEditor";
|
||||
import { Title, useAdmin } from "@/admin/ui";
|
||||
|
||||
/** The team (§6): shown on the Leadership page and the home page's Team section. */
|
||||
export default function Leaders() {
|
||||
const { data } = useAdmin<{ user: { role: string } }>("/me");
|
||||
return (
|
||||
<>
|
||||
<Title sub="The people who lead your church. The first is shown largest in the Featured layout.">Leadership</Title>
|
||||
<ListEditor path="/leaders" nameKey="name" subKey="role" addLabel="Add a person" canAdd={!!data && canEdit(data.user.role)} fields={[
|
||||
{ key: "name", label: "Name", kind: "text", max: 120 },
|
||||
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
|
||||
{ key: "bio", label: "About them", kind: "textarea", max: 4000 },
|
||||
{ key: "photoId", label: "Photo", kind: "image" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
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";
|
||||
|
||||
/** 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 [alts, setAlts] = useState<Record<string, string>>({});
|
||||
const { busy, message, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const s = data.storage;
|
||||
return (
|
||||
<>
|
||||
<Title sub="Photos for your pages. Sermon audio and video are linked (YouTube, Spotify), never uploaded.">Media library</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<Panel>
|
||||
{message && <div className="mb-3"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
{data.items.length === 0 && <p className="text-gray-600">No photos yet.</p>}
|
||||
<ul className="grid gap-4 sm:grid-cols-2">
|
||||
{data.items.map((m) => (
|
||||
<li key={m.id} className="space-y-2">
|
||||
<img src={m.url} alt={m.alt} className="aspect-[4/3] w-full rounded object-cover" />
|
||||
<label className="block text-xs text-gray-600">What it shows
|
||||
<input className={inputClass} value={alts[m.id] ?? m.alt} maxLength={500} onChange={(e) => setAlts({ ...alts, [m.id]: e.target.value })} />
|
||||
</label>
|
||||
{alts[m.id] !== undefined && alts[m.id] !== m.alt && (
|
||||
<Btn busy={busy} onClick={() => run(async () => { await api(`/media/${m.id}`, { method: "PUT", body: { alt: alts[m.id] } }); await reload(); }, "Saved.")}>Save</Btn>
|
||||
)}
|
||||
{!m.alt && <p className="text-xs font-medium text-amber-800">Add what it shows, for people who can't see it.</p>}
|
||||
<p className="text-xs text-gray-500">{m.width && m.height ? `${m.width} × ${m.height}` : ""} · {gb(m.bytes)}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
<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>}
|
||||
</Panel>
|
||||
<Panel title="Upload a photo">
|
||||
{s.full ? <Notice tone="warning">Uploads have stopped: your storage is full.</Notice> : <Uploader onUploaded={() => reload()} />}
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { canEdit } from "@/admin/api";
|
||||
import { ListEditor } from "@/admin/ListEditor";
|
||||
import { Title, useAdmin } from "@/admin/ui";
|
||||
|
||||
/** Ministries (§6): shown on the Ministries page and the home page's Ministries section. */
|
||||
export default function Ministries() {
|
||||
const { data } = useAdmin<{ user: { role: string } }>("/me");
|
||||
return (
|
||||
<>
|
||||
<Title sub="Your ministries' pages. A ministry leader can edit their own; an editor publishes it.">Ministries</Title>
|
||||
<ListEditor path="/ministries" nameKey="name" subKey="summary" addLabel="Add a ministry" canAdd={!!data && canEdit(data.user.role)} fields={[
|
||||
{ key: "name", label: "Name", kind: "text", max: 120 },
|
||||
{ key: "summary", label: "In one line", kind: "text", max: 300, hint: "E.g. “Ages 3 to 12, every Sunday at 10:00.”" },
|
||||
{ key: "body", label: "More about it", kind: "textarea", max: 8000 },
|
||||
{ key: "imageId", label: "Photo", kind: "image" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { StorageMeter, type Storage } from "@/admin/media";
|
||||
import { Loading, Notice, Panel, Title, useAdmin, when } from "@/admin/ui";
|
||||
|
||||
type Overview = {
|
||||
pending: number;
|
||||
lastPublished: { number: number; at: string } | null;
|
||||
storage: Storage;
|
||||
colourNotes: string[];
|
||||
checklist: { key: string; label: string; done: boolean; href: string | null }[];
|
||||
};
|
||||
|
||||
/** The dashboard (§10): the setup checklist, what's waiting to be published, storage. */
|
||||
export default function Dashboard() {
|
||||
const { data, error } = useAdmin<Overview>("/overview");
|
||||
if (!data) return <Loading error={error} />;
|
||||
return (
|
||||
<>
|
||||
<Title sub={data.lastPublished ? `Last published ${when(data.lastPublished.at)} (version ${data.lastPublished.number}).` : "Your site shows Coming soon until you publish it."}>Dashboard</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<Panel title="Getting your site ready">
|
||||
<ol className="space-y-3">
|
||||
{data.checklist.map((c) => (
|
||||
<li key={c.key} className="flex items-start gap-3">
|
||||
<span aria-hidden="true" className={c.done ? "text-green-700" : "text-gray-400"}>{c.done ? "✓" : "○"}</span>
|
||||
<span className={c.done ? "text-gray-500 line-through" : ""}>{c.href ? <Link href={c.href} className="underline-offset-4 hover:underline">{c.label}</Link> : c.label}</span>
|
||||
<span className="sr-only">{c.done ? "(done)" : "(to do)"}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</Panel>
|
||||
<div className="space-y-6">
|
||||
<Panel title="Waiting to be published">
|
||||
{data.pending ? (
|
||||
<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've done.</p>}
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* One page (§6): its title, address, menu and search engine details, then its content. The home
|
||||
* page has one of each homepage section (their layouts are set under Template and style); every
|
||||
* other page is built from blocks, which can be added, moved and removed.
|
||||
*/
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { api } from "@/admin/api";
|
||||
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[] };
|
||||
|
||||
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
|
||||
const LISTS: Record<string, string> = {
|
||||
ministries: "This page lists your ministries (under Ministries); blocks you add show after them.",
|
||||
leadership: "This page lists your team (under Leadership); blocks you add show after them.",
|
||||
events: "This page lists your events; blocks you add show after them.",
|
||||
messages: "This page lists your messages; blocks you add show after them.",
|
||||
contact: "This page shows your church's contact details and service times from your church profile.",
|
||||
};
|
||||
|
||||
function SectionEditor({ title, fields, initial, onSave, extra }: { title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>; onSave: (data: Record<string, unknown>) => Promise<unknown>; extra?: React.ReactNode }) {
|
||||
const [value, setValue] = useState(initial);
|
||||
const [open, setOpen] = useState(false);
|
||||
const { busy, message, fields: errors, run } = useAction();
|
||||
return (
|
||||
<Panel>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h3 className="font-semibold">{title}</h3>
|
||||
<div className="flex gap-2">{extra}<Btn onClick={() => setOpen(!open)} aria-expanded={open}>{open ? "Close" : "Edit"}</Btn></div>
|
||||
</div>
|
||||
{open && (
|
||||
<div className="mt-4 space-y-4">
|
||||
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} />
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EditPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`);
|
||||
const details = useAction();
|
||||
const blocks = useAction();
|
||||
const [form, setForm] = useState<Partial<PageData> | null>(null);
|
||||
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 } });
|
||||
setData(p);
|
||||
setForm(null);
|
||||
}, "Saved as a draft.");
|
||||
const blockCall = (path: string, method: string, body?: unknown) => blocks.run(async () => setData(await api<PageData>(`/pages/${id}${path}`, { method, body })));
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title sub={page.kind === "home" ? "Your home page" : `Your site/${page.slug}`}
|
||||
actions={page.kind !== "home" && <Btn kind="danger" onClick={() => details.run(async () => { await api(`/pages/${id}`, { method: "DELETE" }); router.push("/admin/pages"); })}>Remove page</Btn>}>
|
||||
{page.title}
|
||||
</Title>
|
||||
<div className="space-y-6">
|
||||
<Panel title="Page details">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Title" error={details.fields.title}><input className={inputClass} value={f.title ?? ""} maxLength={120} onChange={(e) => setForm({ ...form, title: e.target.value })} /></Field>
|
||||
{page.kind !== "home" && <Field label="Address" hint={`Your site/${f.slug}`} error={details.fields.slug}><input className={inputClass} value={f.slug ?? ""} onChange={(e) => setForm({ ...form, slug: e.target.value })} /></Field>}
|
||||
{page.kind !== "home" && <Field label="Name in the menu" hint="Leave empty to use the title."><input className={inputClass} value={f.navLabel ?? ""} maxLength={40} onChange={(e) => setForm({ ...form, navLabel: e.target.value || null })} /></Field>}
|
||||
{page.kind !== "home" && <label className="flex items-center gap-2 self-end pb-2 text-sm"><input type="checkbox" checked={!!f.inNav} onChange={(e) => setForm({ ...form, inNav: e.target.checked })} />Show in the menu</label>}
|
||||
<Field label="Title in search results" hint={`${(f.seoTitle ?? f.title ?? "").length} of 60 characters`} error={details.fields.seoTitle}><input className={inputClass} value={f.seoTitle ?? ""} maxLength={70} onChange={(e) => setForm({ ...form, seoTitle: e.target.value || null })} placeholder={f.title} /></Field>
|
||||
<Field label="Description in search results" hint={`${(f.description ?? "").length} of 155 characters${f.description ? "" : ": add one, so search engines show what this page is about"}`} error={details.fields.description}>
|
||||
<textarea className={inputClass} rows={2} value={f.description ?? ""} maxLength={300} onChange={(e) => setForm({ ...form, description: e.target.value || null })} />
|
||||
</Field>
|
||||
<div className="sm:col-span-2"><ImagePicker label="Image when shared (optional)" value={f.imageId ?? null} onChange={(imageId) => setForm({ ...form, imageId })} /></div>
|
||||
</div>
|
||||
{/* A Google-style preview of the search result (ROADMAP-v3 §11). */}
|
||||
<div className="mt-4 rounded border border-gray-200 p-3" aria-label="How it may look in search results">
|
||||
<p className="truncate text-lg text-blue-800">{f.seoTitle || f.title}</p>
|
||||
<p className="line-clamp-2 text-sm text-gray-600">{f.description || "No description yet."}</p>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center gap-3">
|
||||
<Btn kind="primary" busy={details.busy} onClick={saveDetails}>Save details</Btn>
|
||||
{details.message && <Notice tone={details.message.tone}>{details.message.text}</Notice>}
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
{page.kind === "home" ? (
|
||||
<>
|
||||
<p className="text-sm text-gray-600">Each section's layout, order and whether it shows are under Template and style.</p>
|
||||
{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 } }))} />;
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{LISTS[page.kind] && <Notice>{LISTS[page.kind]}</Notice>}
|
||||
{page.sections.map((s, i) => {
|
||||
const spec = BLOCK_FIELDS[s.type];
|
||||
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 } }))}
|
||||
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>
|
||||
<Btn onClick={() => blockCall(`/blocks/${s.id}`, "PUT", { hidden: !s.hidden })}>{s.hidden ? "Show" : "Hide"}</Btn>
|
||||
<Btn kind="danger" onClick={() => blockCall(`/blocks/${s.id}`, "DELETE")}>Remove</Btn>
|
||||
</>} />
|
||||
);
|
||||
})}
|
||||
<Panel title="Add a block">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(BLOCK_FIELDS).map(([type, spec]) => <Btn key={type} busy={blocks.busy} onClick={() => blockCall("/blocks", "POST", { type })}>{spec.name}</Btn>)}
|
||||
</div>
|
||||
{blocks.message && <div className="mt-3"><Notice tone={blocks.message.tone}>{blocks.message.text}</Notice></div>}
|
||||
</Panel>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { api } from "@/admin/api";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type PageRow = { id: string; kind: string; slug: string; title: string; inNav: boolean; path: string };
|
||||
|
||||
const KINDS: Record<string, string> = { home: "Home", visit: "Plan your visit", about: "About", leadership: "Leadership", ministries: "Ministries", events: "Events", messages: "Messages", give: "Give", contact: "Contact", terms: "Terms", safeguarding: "Safeguarding", custom: "Your own page" };
|
||||
|
||||
/** Pages (§6): the fixed ones and the church's own, built from blocks. */
|
||||
export default function Pages() {
|
||||
const { data, error } = useAdmin<PageRow[]>("/pages");
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const { busy, message, fields, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const create = () => run(async () => {
|
||||
const p = await api<{ id: string }>("/pages", { body: { title, slug } });
|
||||
router.push(`/admin/pages/${p.id}`);
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<Title sub="Each page is a draft until you publish.">Pages</Title>
|
||||
<div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
|
||||
<Panel>
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{data.map((p) => (
|
||||
<li key={p.id} className="flex items-center justify-between gap-3 py-3">
|
||||
<div>
|
||||
<Link href={`/admin/pages/${p.id}`} className="font-medium underline-offset-4 hover:underline">{p.title}</Link>
|
||||
<p className="text-xs text-gray-500">{KINDS[p.kind] ?? p.kind} · {p.path}{!p.inNav && p.kind !== "home" && " · not in the menu"}</p>
|
||||
</div>
|
||||
<Link href={`/admin/pages/${p.id}`} className="text-sm font-semibold text-brand-text">Edit</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Panel>
|
||||
<Panel title="Add a page">
|
||||
<div className="space-y-3">
|
||||
<Field label="Title" error={fields.title}><input className={inputClass} value={title} maxLength={120} onChange={(e) => { setTitle(e.target.value); setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "")); }} /></Field>
|
||||
<Field label="Address" hint={`Your site/${slug || "…"}`} error={fields.slug}><input className={inputClass} value={slug} maxLength={80} onChange={(e) => setSlug(e.target.value)} /></Field>
|
||||
<Btn kind="primary" busy={busy} onClick={create} disabled={!title || !slug}>Add page</Btn>
|
||||
{message && <Notice tone={message.tone}>{message.text}</Notice>}
|
||||
</div>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Publish and history (WEBSITE-1.0-PLAN §4): every pending change (what, who, when), Discard for
|
||||
* any one, one Publish for the whole site; links to share the preview; every published version,
|
||||
* any of which can be restored into the working copy.
|
||||
*/
|
||||
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 Change = { key: string; kind: "added" | "changed" | "removed"; what: string; label: string; by: string | null; at: string | null };
|
||||
type Version = { number: number; publishedAt: string; by: string | null; note: string | null };
|
||||
type Link = { id: string; createdAt: string; expiresAt: string; by: string | null; active: boolean };
|
||||
|
||||
const WHAT: Record<string, string> = { design: "Template and style", page: "Page", ministry: "Ministry", leader: "Team" };
|
||||
const KIND: Record<string, string> = { added: "Added", changed: "Changed", removed: "Removed" };
|
||||
|
||||
export default function Publish() {
|
||||
const me = useAdmin<{ user: { role: string } }>("/me");
|
||||
const pending = useAdmin<Change[]>("/changes");
|
||||
const versions = useAdmin<Version[]>("/versions");
|
||||
const editor = !!me.data && canEdit(me.data.user.role);
|
||||
const links = useAdmin<Link[]>(editor ? "/preview-links" : null);
|
||||
const [note, setNote] = useState("");
|
||||
const [newLink, setNewLink] = useState<string | null>(null);
|
||||
const { busy, message, run } = useAction();
|
||||
if (!pending.data || !versions.data) return <Loading error={pending.error ?? versions.error} />;
|
||||
const first = versions.data.length === 0;
|
||||
const reloadAll = async () => { await Promise.all([pending.reload(), versions.reload(), links.reload()]); };
|
||||
|
||||
return (
|
||||
<>
|
||||
<Title sub={first ? "Until you publish, visitors see Coming soon." : "Visitors see the last version published."}
|
||||
actions={<>
|
||||
{/* eslint-disable-next-line @next/next/no-html-link-for-pages -- a route handler that sets the preview cookie: a full page load, not a client navigation */}
|
||||
<a href="/preview/start" className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-semibold hover:bg-gray-50">Preview the whole site</a>
|
||||
</>}>
|
||||
Publish and history
|
||||
</Title>
|
||||
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
<div className="space-y-6">
|
||||
<Panel title={pending.data.length ? `${pending.data.length} ${pending.data.length === 1 ? "change" : "changes"} not published` : "Nothing waiting to be published"}>
|
||||
{pending.data.length > 0 && (
|
||||
<ul className="mb-4 divide-y divide-gray-200">
|
||||
{pending.data.map((c) => (
|
||||
<li key={c.key} className="flex flex-wrap items-center justify-between gap-3 py-2">
|
||||
<div>
|
||||
<p><span className="font-medium">{KIND[c.kind]}:</span> {WHAT[c.what]} {c.what !== "design" && <>“{c.label}”</>}</p>
|
||||
<p className="text-xs text-gray-500">{[c.by, when(c.at)].filter(Boolean).join(", ")}</p>
|
||||
</div>
|
||||
{editor && <Btn busy={busy} onClick={() => run(async () => { await api("/discard", { body: { key: c.key } }); await reloadAll(); }, "Discarded: back to the published version.")}>Discard</Btn>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{editor ? (
|
||||
(pending.data.length > 0 || first) && (
|
||||
<div className="space-y-3">
|
||||
<Field label="A note for the history (optional)"><input className={inputClass} value={note} maxLength={500} onChange={(e) => setNote(e.target.value)} placeholder="E.g. Christmas service times" /></Field>
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(async () => {
|
||||
const r = await api<{ number: number }>("/publish", { body: { note } });
|
||||
// Visitors get it at once, not after the 30-second cache.
|
||||
await fetch("/revalidate", { method: "POST" }).catch(() => {});
|
||||
setNote("");
|
||||
await reloadAll();
|
||||
return r;
|
||||
}, first ? "Published: your site is live." : "Published: visitors see it now.")}>{first ? "Publish your site" : "Publish all changes"}</Btn>
|
||||
</div>
|
||||
)
|
||||
) : <p className="text-sm text-gray-600">An editor publishes your changes.</p>}
|
||||
</Panel>
|
||||
|
||||
{editor && (
|
||||
<Panel title="Share the preview">
|
||||
<p className="mb-3 text-sm text-gray-600">A link for someone without an account (your pastor, say) to see the whole site as it would look published. It works for 7 days, or until you stop it, and can't change anything.</p>
|
||||
<Btn busy={busy} onClick={() => run(async () => { const l = await api<{ url: string }>("/preview-links", { body: {} }); setNewLink(l.url); await links.reload(); })}>Make a preview link</Btn>
|
||||
{newLink && (
|
||||
<div className="mt-3"><Notice tone="success">Copy this link now (it isn't shown again): <code className="break-all font-mono">{newLink}</code></Notice></div>
|
||||
)}
|
||||
{links.data && links.data.length > 0 && (
|
||||
<ul className="mt-4 divide-y divide-gray-200 text-sm">
|
||||
{links.data.map((l) => (
|
||||
<li key={l.id} className="flex items-center justify-between gap-3 py-2">
|
||||
<span>Made {when(l.createdAt)}{l.by && ` by ${l.by}`} · {l.active ? `works until ${when(l.expiresAt)}` : "stopped"}</span>
|
||||
{l.active && <Btn kind="danger" onClick={() => run(async () => { await api(`/preview-links/${l.id}`, { method: "DELETE" }); await links.reload(); }, "The link stopped working.")}>Stop it</Btn>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
<Panel title="History">
|
||||
{versions.data.length === 0 ? <p className="text-gray-600">Not published yet.</p> : (
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{versions.data.map((v, i) => (
|
||||
<li key={v.number} className="flex flex-wrap items-center justify-between gap-3 py-2">
|
||||
<div>
|
||||
<p className="font-medium">Version {v.number}{i === 0 && " (live)"}{v.note && <span className="font-normal text-gray-600"> · {v.note}</span>}</p>
|
||||
<p className="text-xs text-gray-500">{when(v.publishedAt)}{v.by && `, ${v.by}`}</p>
|
||||
</div>
|
||||
{editor && i > 0 && <Btn onClick={() => run(async () => { await api(`/versions/${v.number}/restore`, { body: {} }); await reloadAll(); }, `Version ${v.number} is back in your drafts: preview it, then publish.`)}>Restore</Btn>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Template and style (WEBSITE-1.0-PLAN §3): the template, each homepage section's layout
|
||||
* (recommended first), the homepage order, and the style settings. Fonts and corners are the
|
||||
* church's brand style, shared with its other sites, so they're set in its church profile.
|
||||
*/
|
||||
import { api } from "@/admin/api";
|
||||
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[]; style: Record<string, string> };
|
||||
type Options = { variants: Record<string, Record<string, string[]>>; headers: Record<string, string[]> };
|
||||
|
||||
const TEMPLATES = [
|
||||
{ id: "heritage", name: "Heritage", text: "Traditional and dignified: centred, framed images, serif headings." },
|
||||
{ id: "bold", name: "Bold", text: "Modern and energetic: full-screen photos, big headlines, bands." },
|
||||
{ id: "community", name: "Community", text: "Warm and friendly: cards, rounded shapes, faces up front." },
|
||||
{ id: "clean", name: "Clean", text: "Minimal and calm: lots of space, good without photos." },
|
||||
];
|
||||
|
||||
const SECTIONS: Record<string, string> = { hero: "Top of the page", serviceTimes: "Service times", welcome: "Welcome", ministries: "Ministries", team: "Team", events: "Upcoming events", latestMessage: "Latest message", invitation: "Invitation" };
|
||||
const VARIANT_NAMES: Record<string, string> = {
|
||||
photo: "Photo", video: "Video", collage: "Collage", split: "Split", text: "Text only", panel: "Panel", strip: "Inline strip", map: "With map",
|
||||
"image-text": "Image and text", pastor: "With pastor", cards: "Cards", list: "List", bands: "Alternating bands", faces: "Faces", featured: "Featured",
|
||||
calendar: "Calendar strip", compact: "Compact", banner: "Banner", centred: "Centred", image: "Image background",
|
||||
};
|
||||
const ALL_VARIANTS: Record<string, string[]> = {
|
||||
hero: ["photo", "video", "collage", "split", "text"], serviceTimes: ["panel", "strip", "map"], welcome: ["text", "image-text", "pastor"], ministries: ["cards", "list", "bands"],
|
||||
team: ["faces", "list", "featured"], events: ["cards", "list", "calendar"], latestMessage: ["video", "card", "compact"], invitation: ["banner", "centred", "image"],
|
||||
};
|
||||
const HEADER_NAMES: Record<string, string> = {
|
||||
centred: "Centred", "centred-top-bar": "Centred, with a top bar", transparent: "Over the photo, solid when scrolling", solid: "Solid",
|
||||
"logo-left-button": "Logo left, with a Plan your visit button", "logo-left-tinted": "Logo left, on a tinted bar", small: "Small", "small-menu": "Small, menu on every screen",
|
||||
};
|
||||
const STYLE = [
|
||||
{ key: "sectionColour", label: "Section colour", options: { light: "Light", tinted: "Tinted (your colour, softly)", mixed: "Mixed, with dark bands" } },
|
||||
{ key: "spacing", label: "Spacing", options: { airy: "Airy", compact: "Compact" } },
|
||||
{ key: "buttons", label: "Buttons", options: { solid: "Solid", outline: "Outline", pill: "Pill" } },
|
||||
{ key: "images", label: "Photos", options: { natural: "Natural", mono: "Black and white", duotone: "Duotone in your colour" } },
|
||||
];
|
||||
|
||||
export default function TemplatePage() {
|
||||
const { data, error, setData } = useAdmin<{ design: Design; options: Options }>("/design");
|
||||
const { busy, message, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const { design, options } = data;
|
||||
const save = (patch: Partial<Design> & { template?: string }, done = "Saved. Preview to see it, then publish.") => run(async () => {
|
||||
const r = await api<{ design: Design; moved: { what: string }[] }>("/design", { method: "PUT", body: patch });
|
||||
setData({ ...data, design: r.design });
|
||||
return r;
|
||||
}, done);
|
||||
const move = (i: number, d: -1 | 1) => {
|
||||
const home = [...design.home];
|
||||
const j = i + d;
|
||||
if (j < 0 || j >= home.length) return;
|
||||
[home[i], home[j]] = [home[j]!, home[i]!];
|
||||
save({ home });
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Title sub="Changes here are drafts: preview them, then publish.">Template and style</Title>
|
||||
{message && <div className="mb-4"><Notice tone={message.tone}>{message.text}</Notice></div>}
|
||||
<div className="space-y-6">
|
||||
<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")}>
|
||||
<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>
|
||||
))}
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Home page: sections and layouts">
|
||||
<p className="mb-4 text-sm text-gray-600">Every layout works in every template; the first ones listed suit {TEMPLATES.find((t) => t.id === design.template)?.name} best.</p>
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{design.home.map((e, i) => {
|
||||
const recommended = options.variants[design.template]?.[e.section] ?? [];
|
||||
const ordered = [...recommended, ...ALL_VARIANTS[e.section]!.filter((v) => !recommended.includes(v))];
|
||||
return (
|
||||
<li key={e.section} className="flex flex-wrap items-center gap-3 py-3">
|
||||
<span className="w-40 font-medium">{SECTIONS[e.section]}</span>
|
||||
<select aria-label={`${SECTIONS[e.section]} layout`} className={`${inputClass} w-56`} value={design.variants[e.section]} disabled={busy}
|
||||
onChange={(ev) => save({ variants: { [e.section]: ev.target.value } })}>
|
||||
{ordered.map((v) => <option key={v} value={v}>{VARIANT_NAMES[v]}{recommended.includes(v) ? " (suits this template)" : ""}</option>)}
|
||||
</select>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={!e.hidden} disabled={busy} onChange={(ev) => save({ home: design.home.map((x) => (x.section === e.section ? { ...x, hidden: !ev.target.checked } : x)) })} />
|
||||
Show
|
||||
</label>
|
||||
<span className="ml-auto flex gap-1">
|
||||
<Btn onClick={() => move(i, -1)} disabled={busy || i === 0} aria-label={`Move ${SECTIONS[e.section]} up`}>↑</Btn>
|
||||
<Btn onClick={() => move(i, 1)} disabled={busy || i === design.home.length - 1} aria-label={`Move ${SECTIONS[e.section]} down`}>↓</Btn>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Style">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="Header">
|
||||
<select className={inputClass} value={design.style.header} disabled={busy} onChange={(e) => save({ style: { header: e.target.value } })}>
|
||||
{(options.headers[design.template] ?? []).map((h) => <option key={h} value={h}>{HEADER_NAMES[h] ?? h}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
{STYLE.map((s) => (
|
||||
<Field key={s.key} label={s.label}>
|
||||
<select className={inputClass} value={design.style[s.key]} disabled={busy} onChange={(e) => save({ style: { [s.key]: e.target.value } })}>
|
||||
{Object.entries(s.options).map(([v, label]) => <option key={v} value={v}>{label}</option>)}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-gray-600">Fonts and corners are your church's brand style, shared with your Events and sign-in pages: change them in your church profile.</p>
|
||||
</Panel>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { signInHref } from "@/lib/admin";
|
||||
|
||||
export const metadata: Metadata = { title: "Signing in", robots: { index: false, follow: false } };
|
||||
|
||||
/** What went wrong with a sign-in (the backend's auth/routes.ts sends people here with a code). */
|
||||
const PROBLEMS: Record<string, { title: string; text: string; retry: boolean }> = {
|
||||
NO_ACCESS: {
|
||||
title: "No access to this website's admin",
|
||||
text: "You're signed in, but your account hasn't been given a role on this website. Ask the website's Owner to add you, then try again.",
|
||||
retry: true,
|
||||
},
|
||||
TWO_FACTOR_NEEDED: {
|
||||
title: "Two-step sign-in needed",
|
||||
text: "Owners and Admins of this website sign in with a second step. Turn on two-step sign-in in your church account, then try again.",
|
||||
retry: true,
|
||||
},
|
||||
ACCOUNTS_UNAVAILABLE: {
|
||||
title: "Signing in isn't available right now",
|
||||
text: "The website can't reach your church's sign-in at the moment. Please try again in a few minutes.",
|
||||
retry: true,
|
||||
},
|
||||
EXPIRED: { title: "The sign-in took too long", text: "Please try again.", retry: true },
|
||||
SIGNIN_FAILED: { title: "That didn't work", text: "Something went wrong while signing you in. Please try again.", retry: true },
|
||||
};
|
||||
|
||||
export default async function Problem({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
|
||||
const q = await searchParams;
|
||||
const code = typeof q.code === "string" ? q.code : "";
|
||||
const returnTo = typeof q.returnTo === "string" && q.returnTo.startsWith("/") && !q.returnTo.startsWith("//") ? q.returnTo : "/admin";
|
||||
const p = PROBLEMS[code] ?? PROBLEMS.SIGNIN_FAILED!;
|
||||
return (
|
||||
<main className="mx-auto max-w-xl px-4 py-16">
|
||||
<h1 className="text-2xl font-semibold">{p.title}</h1>
|
||||
<p className="mt-2 text-gray-600">{p.text}</p>
|
||||
<div className="mt-6 flex gap-3">
|
||||
{p.retry && (
|
||||
<a href={signInHref(returnTo)} className="rounded bg-brand px-4 py-2 text-sm text-white hover:bg-brand-dark">
|
||||
Try again
|
||||
</a>
|
||||
)}
|
||||
<Link href="/" className="rounded border border-gray-300 px-4 py-2 text-sm hover:bg-gray-50">
|
||||
Go to the website
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
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 { 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;
|
||||
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 } };
|
||||
}
|
||||
|
||||
/** A simple event made in the Website (§8). Cross Events' own events link to Cross Events instead. */
|
||||
export default async function EventPage({ params }: Props) {
|
||||
const { site, event } = await find((await params).slug);
|
||||
if (!site || !event) notFound();
|
||||
const zone = site.church?.timezone ?? "Africa/Johannesburg";
|
||||
const events = site.snapshot.pages.find((p) => p.kind === "events");
|
||||
return (
|
||||
<Shell site={site} path={event.url}>
|
||||
<article className="cc-section">
|
||||
<div className="cc-wrap grid gap-10 md:grid-cols-2">
|
||||
<Img image={event.image} priority />
|
||||
<div>
|
||||
<p className="cc-eyebrow">{fmtDate(event.startsAt, zone, { weekday: "long", day: "numeric", month: "long", year: "numeric" })}{!event.allDay && `, ${fmtTime(event.startsAt, zone)}`}</p>
|
||||
<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>}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/*
|
||||
* The four templates (WEBSITE-1.0-PLAN §3). The layout sets, on <html>:
|
||||
* data-template heritage | bold | community | clean
|
||||
* data-spacing airy | compact (style setting)
|
||||
* data-buttons solid | outline | pill (style setting)
|
||||
* data-images natural | mono | duotone
|
||||
* data-section-colour light | tinted | mixed
|
||||
* data-cc-fonts / data-cc-corners (the church's shared brand style, @crosscode/ui)
|
||||
* and the colours as CSS variables (--brand, --on-brand, --brand-text, --brand-tint, --accent, …).
|
||||
* Section components use the cc-* classes below; each template restyles them.
|
||||
*/
|
||||
|
||||
:root {
|
||||
--brand: 31 78 121;
|
||||
--brand-dark: 25 62 97;
|
||||
--on-brand: 255 255 255;
|
||||
--brand-text: 31 78 121;
|
||||
--brand-tint: 241 244 248;
|
||||
--accent: 87 113 148;
|
||||
--on-accent: 255 255 255;
|
||||
--cc-section-y: 5rem;
|
||||
--cc-wrap: 72rem;
|
||||
--cc-text: 42rem;
|
||||
}
|
||||
|
||||
[data-spacing="compact"] { --cc-section-y: 3rem; }
|
||||
@media (max-width: 640px) {
|
||||
:root { --cc-section-y: 3.5rem; }
|
||||
[data-spacing="compact"] { --cc-section-y: 2.25rem; }
|
||||
}
|
||||
|
||||
[data-template="heritage"] { --cc-wrap: 60rem; --cc-text: 40rem; }
|
||||
[data-template="bold"] { --cc-wrap: 80rem; --cc-text: 46rem; }
|
||||
[data-template="community"] { --cc-wrap: 72rem; --cc-text: 42rem; }
|
||||
[data-template="clean"] { --cc-wrap: 48rem; --cc-text: 40rem; }
|
||||
|
||||
body {
|
||||
@apply bg-white text-gray-900 antialiased;
|
||||
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif);
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.cc-wrap { @apply mx-auto w-full px-4 sm:px-6; max-width: var(--cc-wrap); }
|
||||
.cc-text { @apply mx-auto w-full; max-width: var(--cc-text); }
|
||||
|
||||
.cc-section { padding-block: var(--cc-section-y); }
|
||||
/* Heritage: thin rules between sections, in one centred column. */
|
||||
[data-template="heritage"] .cc-section + .cc-section { border-top: 1px solid rgb(var(--brand-text) / 0.18); }
|
||||
/*
|
||||
* Section colour: tinted alternates the church colour as a soft background; mixed adds dark bands.
|
||||
* Never on a section that sets its own background (cc-own-bg: a banner, a photo, a dark band).
|
||||
*/
|
||||
[data-section-colour="tinted"] .cc-section:not(.cc-own-bg):nth-of-type(even) { background: rgb(var(--brand-tint)); }
|
||||
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) { background: rgb(var(--brand-dark)); color: rgb(var(--on-brand)); }
|
||||
[data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-card { background: rgb(255 255 255 / 0.06); border-color: rgb(255 255 255 / 0.2); color: inherit; }
|
||||
|
||||
/* 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,
|
||||
[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); }
|
||||
|
||||
.cc-muted { color: rgb(75 85 99); }
|
||||
.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; }
|
||||
[data-template="community"] .cc-eyebrow { @apply normal-case tracking-normal; }
|
||||
|
||||
/* Headings: each template's voice. */
|
||||
.cc-h1 { @apply text-4xl leading-tight sm:text-5xl; }
|
||||
.cc-h2 { @apply text-3xl leading-tight sm:text-4xl; }
|
||||
.cc-h3 { @apply text-xl leading-snug; }
|
||||
[data-template="heritage"] .cc-h1, [data-template="heritage"] .cc-h2 { @apply font-normal tracking-wide; }
|
||||
[data-template="heritage"] .cc-h3 { @apply font-normal; }
|
||||
[data-template="bold"] .cc-h1 { @apply text-5xl font-bold uppercase leading-[0.95] sm:text-7xl; letter-spacing: -0.01em; }
|
||||
[data-template="bold"] .cc-h2 { @apply text-4xl font-bold uppercase leading-none sm:text-5xl; }
|
||||
[data-template="bold"] .cc-h3 { @apply font-bold uppercase; }
|
||||
[data-template="community"] .cc-h1, [data-template="community"] .cc-h2 { @apply font-extrabold; }
|
||||
[data-template="community"] .cc-h3 { @apply font-bold; }
|
||||
[data-template="clean"] .cc-h1 { @apply font-semibold sm:text-6xl; letter-spacing: -0.03em; }
|
||||
[data-template="clean"] .cc-h2 { @apply text-2xl font-semibold sm:text-3xl; letter-spacing: -0.02em; }
|
||||
[data-template="clean"] .cc-h3 { @apply font-semibold; }
|
||||
|
||||
/* Buttons: solid, outline or pill (style setting); corners from the church's brand style. */
|
||||
.cc-btn {
|
||||
@apply inline-flex items-center justify-center gap-2 px-6 py-3 text-base font-semibold no-underline transition-colors;
|
||||
border-radius: var(--cc-radius-button, 0.5rem);
|
||||
background: rgb(var(--brand)); color: rgb(var(--on-brand)); border: 2px solid rgb(var(--brand));
|
||||
}
|
||||
.cc-btn:hover { background: rgb(var(--brand-dark)); border-color: rgb(var(--brand-dark)); }
|
||||
.cc-btn:focus-visible { outline: 3px solid rgb(var(--accent)); outline-offset: 2px; }
|
||||
[data-buttons="outline"] .cc-btn { background: transparent; color: rgb(var(--brand-text)); border-color: currentColor; }
|
||||
[data-buttons="outline"] .cc-btn:hover { background: rgb(var(--brand)); color: rgb(var(--on-brand)); border-color: rgb(var(--brand)); }
|
||||
[data-buttons="pill"] .cc-btn { border-radius: 9999px; }
|
||||
[data-template="bold"] .cc-btn { @apply uppercase tracking-wider; }
|
||||
/* A button on a photo or a dark band: always light on dark. */
|
||||
.cc-on-dark .cc-btn, .cc-dark .cc-btn, [data-section-colour="mixed"] .cc-section:not(.cc-own-bg):nth-of-type(3n) .cc-btn {
|
||||
background: rgb(255 255 255); color: rgb(17 24 39); border-color: rgb(255 255 255);
|
||||
}
|
||||
|
||||
/* Cards. */
|
||||
.cc-card { @apply overflow-hidden bg-white; border-radius: var(--cc-radius, 0.5rem); }
|
||||
[data-template="heritage"] .cc-card { border: 1px solid rgb(var(--brand-text) / 0.2); }
|
||||
[data-template="bold"] .cc-card { @apply bg-gray-900 text-white; }
|
||||
[data-template="community"] .cc-card { @apply shadow-md; box-shadow: 0 10px 30px -12px rgb(var(--brand) / 0.35); }
|
||||
[data-template="clean"] .cc-card { border-bottom: 1px solid rgb(229 231 235); border-radius: 0; }
|
||||
|
||||
/* Images: natural, black and white, or duotone in the church colour (style setting). */
|
||||
.cc-img { @apply block h-full w-full object-cover; border-radius: var(--cc-radius-sm, 0); }
|
||||
.cc-frame { @apply relative overflow-hidden; border-radius: var(--cc-radius, 0); }
|
||||
[data-images="mono"] .cc-img { filter: grayscale(1) contrast(1.05); }
|
||||
[data-images="duotone"] .cc-img { filter: grayscale(1) contrast(1.1); mix-blend-mode: multiply; }
|
||||
[data-images="duotone"] .cc-frame { background: rgb(var(--brand)); }
|
||||
/* Heritage frames its images. */
|
||||
[data-template="heritage"] .cc-frame { padding: 0.5rem; background: white; border: 1px solid rgb(var(--brand-text) / 0.25); }
|
||||
[data-template="heritage"][data-images="duotone"] .cc-frame { background: rgb(var(--brand)); }
|
||||
|
||||
/* Prose for text the admins write (paragraphs only; no HTML is ever rendered). */
|
||||
.cc-prose p + p { margin-top: 1em; }
|
||||
.cc-prose { @apply text-lg leading-relaxed; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.cc-motion { display: none !important; }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { loadContent } from "@/site/load";
|
||||
import { PreviewBar } from "@/site/PreviewBar";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const c = await loadContent();
|
||||
const name = c.church?.name ?? "Church Website";
|
||||
return {
|
||||
title: { default: name, template: `%s · ${name}` },
|
||||
icons: c.church?.branding.iconUrl ? { icon: c.church.branding.iconUrl } : undefined,
|
||||
// A preview is never indexed (§4).
|
||||
...(c.mode === "published" && c.preview ? { robots: { index: false, follow: false } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Every page: the church's fonts and corners (shared brand style), the template and the style
|
||||
* settings as attributes (globals.css), and its colours, made safe by the backend, as variables.
|
||||
* While previewing, the site's pages get the preview bar above them.
|
||||
*/
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const c = await loadContent();
|
||||
const path = (await headers()).get("x-ccw-path") ?? "/";
|
||||
const p = c.palette;
|
||||
const template = c.mode === "published" ? c.snapshot.design.template : c.template;
|
||||
const s = c.mode === "published" ? c.snapshot.design.style : null;
|
||||
const vars = `:root{--brand:${p.brand};--brand-dark:${p.brandDark};--on-brand:${p.onBrand};--brand-text:${p.brandText};--brand-tint:${p.brandTint};--accent:${p.accent};--on-accent:${p.onAccent}}`;
|
||||
const bar = c.mode === "published" && c.preview && !path.startsWith("/admin") && !path.startsWith("/preview") ? c.preview : null;
|
||||
return (
|
||||
<html
|
||||
lang="en-ZA"
|
||||
{...brandAttributes(c.style)}
|
||||
data-template={template}
|
||||
data-spacing={s?.spacing ?? "airy"}
|
||||
data-buttons={s?.buttons ?? "solid"}
|
||||
data-images={s?.images ?? "natural"}
|
||||
data-section-colour={s?.sectionColour ?? "light"}
|
||||
>
|
||||
<head>
|
||||
<style>{vars.replace(/[<>]/g, "")}</style>
|
||||
</head>
|
||||
<body>
|
||||
{bar && <PreviewBar preview={bar} />}
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import Link from "next/link";
|
||||
import { loadPublished } from "@/site/load";
|
||||
import { Shell } from "@/site/Shell";
|
||||
|
||||
export default async function NotFound() {
|
||||
const site = await loadPublished();
|
||||
const body = (
|
||||
<section className="cc-section">
|
||||
<div className="cc-wrap text-center">
|
||||
<h1 className="cc-h1">Page not found</h1>
|
||||
<p className="cc-muted mt-4 text-lg">That page isn't here. It may have moved.</p>
|
||||
<Link href="/" className="cc-btn mt-8">Go to the home page</Link>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
return site ? <Shell site={site} path="/404">{body}</Shell> : <main>{body}</main>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Metadata } from "next";
|
||||
import { cookies } from "next/headers";
|
||||
import { ComingSoon } from "@/site/ComingSoon";
|
||||
import { loadContent } from "@/site/load";
|
||||
import { churchLd, pageMetadata } from "@/site/meta";
|
||||
import { Sections } from "@/site/sections";
|
||||
import { Shell } from "@/site/Shell";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const c = await loadContent();
|
||||
if (c.mode === "coming-soon") {
|
||||
// A real page (HTTP 200) that's never indexed (§5, decision 14).
|
||||
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) : {};
|
||||
}
|
||||
|
||||
export default async function Home() {
|
||||
const c = await loadContent();
|
||||
if (c.mode === "coming-soon") return <ComingSoon c={c} signedInAdmin={(await cookies()).has("ccw_session")} />;
|
||||
const home = c.snapshot.pages.find((p) => p.kind === "home");
|
||||
const sections = home?.sections ?? [];
|
||||
const ld = churchLd(c, "/");
|
||||
return (
|
||||
<Shell site={c} path="/">
|
||||
{ld && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ld }} />}
|
||||
{/* Exactly one <h1> (§11): the hero's, else the church's name. */}
|
||||
{sections[0]?.type !== "hero" && <h1 className="sr-only">{c.church?.name ?? "Home"}</h1>}
|
||||
<Sections site={c} sections={sections} />
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* 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 }> }) {
|
||||
const { token } = await params;
|
||||
const res = NextResponse.redirect(new URL("/", request.url), 303);
|
||||
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 });
|
||||
}
|
||||
res.headers.set("X-Robots-Tag", "noindex, nofollow");
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/** 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);
|
||||
res.cookies.delete("ccw_preview");
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Metadata } from "next";
|
||||
import { PreviewBar } from "@/site/PreviewBar";
|
||||
import { loadContent } from "@/site/load";
|
||||
|
||||
export const metadata: Metadata = { title: "Preview", robots: { index: false, follow: false } };
|
||||
|
||||
const WIDTHS: Record<string, number> = { phone: 390, tablet: 820 };
|
||||
|
||||
/**
|
||||
* The preview at phone or tablet width (§4): the site in a frame of that width, so its layout is
|
||||
* exactly what a phone shows. The bar stays outside the frame.
|
||||
*/
|
||||
export default async function Frame({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
|
||||
const q = await searchParams;
|
||||
const size = q.size === "tablet" ? "tablet" : "phone";
|
||||
const c = await loadContent();
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-200">
|
||||
{c.mode === "published" && c.preview && <PreviewBar preview={c.preview} size={size} />}
|
||||
<div className="flex justify-center py-6">
|
||||
<iframe src="/" title={`The site at ${size} width`} style={{ width: WIDTHS[size], height: "calc(100vh - 7rem)" }} className="rounded-lg border border-gray-300 bg-white shadow-xl" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* Preview (WEBSITE-1.0-PLAN §4): a signed-in admin sees the working copy on the site's own
|
||||
* addresses, fully clickable. The cookie only asks for it; the backend checks the admin's session
|
||||
* 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: "/" });
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { revalidateTag } from "next/cache";
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
/**
|
||||
* Publish (WEBSITE-1.0-PLAN §1, §4) refreshes the public pages at once: the admin calls this right
|
||||
* after publishing, and the next visitor gets the new version (no stale copy). Only a signed-in
|
||||
* admin can ask.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const session = request.cookies.get("ccw_session")?.value;
|
||||
const me = session ? await fetch(`${api}/api/auth/me`, { headers: { Cookie: `ccw_session=${encodeURIComponent(session)}` }, cache: "no-store" }).catch(() => null) : null;
|
||||
if (!me?.ok) return NextResponse.json({ error: { code: "SIGNED_OUT", message: "Please sign in." } }, { status: 401 });
|
||||
revalidateTag("site-content", { expire: 0 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
|
||||
// The public site is indexed; the admin, previews and API never are (ROADMAP-v3 §11). The sitemap
|
||||
// comes with the published pages.
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return { rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/preview", "/auth", "/api"] }] };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { loadContent } from "@/site/load";
|
||||
import { siteBase } from "@/site/meta";
|
||||
|
||||
/**
|
||||
* The published pages and the Website's own events (ROADMAP-v3 §11). Events copied from Cross
|
||||
* Events aren't listed: their canonical page is at the origin. Before the first publish: empty.
|
||||
*/
|
||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
const c = await loadContent();
|
||||
if (c.mode !== "published") return [];
|
||||
const base = siteBase(c);
|
||||
if (!base) return [];
|
||||
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 })),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
/** The signed-in admin (from the backend's /api/auth/me), for the admin's server-rendered pages. */
|
||||
export type Me = {
|
||||
user: { id: string; name: string; email: string; role: "owner" | "admin" | "editor" | "ministry_leader" | "viewer"; ministryId: string | null };
|
||||
mfa: boolean;
|
||||
};
|
||||
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
export const ROLE_NAMES: Record<Me["user"]["role"], string> = {
|
||||
owner: "Owner",
|
||||
admin: "Admin",
|
||||
editor: "Editor",
|
||||
ministry_leader: "Ministry leader",
|
||||
viewer: "Viewer",
|
||||
};
|
||||
|
||||
/** Null when signed out (or the backend can't say); the page then sends people to sign in. */
|
||||
export async function loadMe(): Promise<Me | null> {
|
||||
const session = (await cookies()).get("ccw_session")?.value;
|
||||
if (!session) return null;
|
||||
try {
|
||||
const res = await fetch(`${api}/api/auth/me`, { headers: { Cookie: `ccw_session=${encodeURIComponent(session)}` }, cache: "no-store" });
|
||||
if (res.ok) return (await res.json()) as Me;
|
||||
} catch {
|
||||
// The backend is starting or down: treated as signed out.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Where "Sign in" goes for a page of the admin: Accounts, and back to that page. */
|
||||
export const signInHref = (returnTo: string) => `/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}`;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* The address a page was asked for, for the layouts: the admin's, so signing in comes back to
|
||||
* that exact page (ROADMAP-v3 §3, "Sign-in always returns you to where you came from"), and the
|
||||
* root layout's, which shows the preview bar on the site's pages only.
|
||||
*/
|
||||
export function proxy(request: NextRequest) {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set("x-ccw-path", `${request.nextUrl.pathname}${request.nextUrl.search}`);
|
||||
return NextResponse.next({ request: { headers } });
|
||||
}
|
||||
|
||||
// Never Next's own paths (/_next: its files and the development connection).
|
||||
export const config = { matcher: ["/((?!api|_next|favicon.ico).*)"] };
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Coming soon (WEBSITE-1.0-PLAN §5): until the first publish, the church's details from its
|
||||
* profile (logo, service times, address, contact, social), links to its Events and App, and a line
|
||||
* the admin can change. `noindex`, a real HTTP 200.
|
||||
*/
|
||||
import Link from "next/link";
|
||||
import { dayName } from "./parts";
|
||||
import type { ComingSoon as Content } from "./types";
|
||||
|
||||
export function ComingSoon({ c, signedInAdmin }: { c: Content; signedInAdmin: boolean }) {
|
||||
const church = c.church;
|
||||
const a = church?.contact.address;
|
||||
const links = church ? ([["Events", church.links.events], ["App", church.links.app]] as const).filter(([, u]) => u) : [];
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-brand-tint px-4 py-16 text-center">
|
||||
{signedInAdmin && (
|
||||
<p className="mb-8 rounded-cc bg-white px-4 py-3 text-sm shadow">
|
||||
Your site isn't published yet. <Link href="/admin" className="cc-link font-semibold">Preview it or publish it</Link>.
|
||||
</p>
|
||||
)}
|
||||
{church?.branding.logoUrl
|
||||
? <img src={church.branding.logoUrl} alt={church.name} className="mb-8 h-20 w-auto max-w-[16rem] object-contain" />
|
||||
: church && <p className="cc-eyebrow mb-4">{church.name}</p>}
|
||||
<h1 className="cc-h1 text-brand-text">{church ? `${church.name}: coming soon` : "Coming soon"}</h1>
|
||||
<p className="cc-muted mt-4 max-w-xl text-lg">{c.comingSoonText}</p>
|
||||
{church && (
|
||||
<div className="mt-10 grid w-full max-w-2xl gap-8 rounded-cc bg-white p-8 text-left shadow sm:grid-cols-2">
|
||||
{church.serviceTimes.length > 0 && (
|
||||
<div>
|
||||
<h2 className="cc-h3 mb-2">Service times</h2>
|
||||
<ul className="space-y-1">{church.serviceTimes.map((s, i) => <li key={i}>{dayName(s.day)} {s.time}{s.label && <span className="cc-muted"> · {s.label}</span>}</li>)}</ul>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h2 className="cc-h3 mb-2">Find us</h2>
|
||||
{a && <address className="not-italic">{[a.line1, a.line2, a.suburb, a.city].filter(Boolean).join(", ")}</address>}
|
||||
<ul className="mt-2 space-y-1">
|
||||
{church.contact.phone && <li><a className="cc-link" href={`tel:${church.contact.phone}`}>{church.contact.phone}</a></li>}
|
||||
{church.contact.email && <li><a className="cc-link break-all" href={`mailto:${church.contact.email}`}>{church.contact.email}</a></li>}
|
||||
{church.social.map((s) => <li key={s.url}><a className="cc-link capitalize" href={s.url} rel="me noopener">{s.network.replace("-", " ")}</a></li>)}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{links.length > 0 && (
|
||||
<div className="mt-8 flex flex-wrap justify-center gap-3">
|
||||
{links.map(([label, url]) => <a key={label} href={url!} className="cc-btn">Our {label}</a>)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Each template's header (WEBSITE-1.0-PLAN §3, "Headers"), with its options from the Header style
|
||||
* setting. Every header collapses to a Menu button on phones (a <details>, so it works without
|
||||
* JavaScript). Links to the church's other sites (Events, App) sit next to the pages (§9).
|
||||
*/
|
||||
import Link from "next/link";
|
||||
import { productLinks } from "@crosscode/ui";
|
||||
import { ScrollSolid } from "./ScrollSolid";
|
||||
import { cx } from "./parts";
|
||||
import type { Published } from "./types";
|
||||
|
||||
type Item = { label: string; href: string; current: boolean };
|
||||
|
||||
function items(site: Published, path: string): { nav: Item[]; visit: Item | null } {
|
||||
const pages = site.snapshot.pages;
|
||||
const nav: Item[] = pages.filter((p) => p.inNav).map((p) => ({ label: p.navLabel, href: p.path, current: p.path === path }));
|
||||
for (const l of site.church ? productLinks(site.church.links, "website") : []) nav.push({ label: l.label, href: l.href, current: false });
|
||||
const v = pages.find((p) => p.kind === "visit");
|
||||
return { nav, visit: v ? { label: v.navLabel, href: v.path, current: v.path === path } : null };
|
||||
}
|
||||
|
||||
function Brand({ site, className, light }: { site: Published; className?: string; light?: boolean }) {
|
||||
const church = site.church;
|
||||
const name = church?.name ?? "Home";
|
||||
return (
|
||||
<Link href="/" className={cx("inline-flex items-center gap-3 no-underline", className)} aria-label={`${name}, home`}>
|
||||
{church?.branding.logoUrl
|
||||
? <img src={church.branding.logoUrl} alt="" className={cx("h-10 w-auto max-w-[12rem] object-contain", light && "brightness-0 invert")} />
|
||||
: <span className="font-heading text-xl font-semibold">{name}</span>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function Links({ nav, className, linkClass }: { nav: Item[]; className?: string; linkClass?: string }) {
|
||||
return (
|
||||
<ul className={className}>
|
||||
{nav.map((n) => (
|
||||
<li key={n.href}>
|
||||
<a href={n.href} aria-current={n.current ? "page" : undefined} className={cx("no-underline hover:underline underline-offset-8", n.current && "underline", linkClass)}>{n.label}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileMenu({ nav, visit, className, always = false }: { nav: Item[]; visit: Item | null; className?: string; always?: boolean }) {
|
||||
return (
|
||||
<details className={cx("group relative", !always && "md:hidden", className)}>
|
||||
<summary className="cursor-pointer list-none rounded-cc-sm border border-current px-3 py-1.5 text-sm font-semibold [&::-webkit-details-marker]:hidden">Menu</summary>
|
||||
<nav aria-label="Main" className="absolute right-0 z-50 mt-2 w-64 rounded-cc bg-white p-4 text-gray-900 shadow-xl">
|
||||
<Links nav={nav} className="space-y-3 text-base" />
|
||||
{visit && <a href={visit.href} className="cc-btn mt-4 w-full">{visit.label}</a>}
|
||||
</nav>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export function Header({ site, path }: { site: Published; path: string }) {
|
||||
const { template, style } = site.snapshot.design;
|
||||
const { nav, visit } = items(site, path);
|
||||
const option = style.header;
|
||||
|
||||
if (template === "heritage") {
|
||||
const nextService = site.church?.serviceTimes[0];
|
||||
return (
|
||||
<header className="bg-white">
|
||||
{option === "centred-top-bar" && (nextService || visit) && (
|
||||
<div className="bg-brand text-sm text-brand-on">
|
||||
<div className="cc-wrap flex items-center justify-center gap-4 py-2">
|
||||
{nextService && <span>Sundays {site.church!.serviceTimes.filter((s) => s.day === "sunday").map((s) => s.time).join(" & ") || nextService.time}</span>}
|
||||
{visit && <a href={visit.href} className="font-semibold underline underline-offset-4">{visit.label}</a>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="cc-wrap flex flex-col items-center gap-5 py-8">
|
||||
<Brand site={site} className="text-center text-2xl" />
|
||||
<nav aria-label="Main" className="hidden w-full border-y border-brand-text/20 py-3 md:block">
|
||||
<Links nav={nav} className="flex flex-wrap justify-center gap-x-8 gap-y-2 text-sm uppercase tracking-[0.18em]" />
|
||||
</nav>
|
||||
<MobileMenu nav={nav} visit={visit} />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
if (template === "bold") {
|
||||
const transparent = !!site.transparentHeader[path];
|
||||
return (
|
||||
<ScrollSolid transparent={transparent} className="sticky top-0 z-40">
|
||||
<div className="cc-wrap flex items-center justify-between gap-6 py-4">
|
||||
<Brand site={site} className="text-white" light={transparent} />
|
||||
<nav aria-label="Main" className="hidden items-center gap-8 md:flex">
|
||||
<Links nav={nav} className="flex gap-6 text-sm font-semibold uppercase tracking-wider" />
|
||||
{visit && <a href={visit.href} className="cc-btn px-5 py-2 text-sm">{visit.label}</a>}
|
||||
</nav>
|
||||
<MobileMenu nav={nav} visit={visit} />
|
||||
</div>
|
||||
</ScrollSolid>
|
||||
);
|
||||
}
|
||||
|
||||
if (template === "community") {
|
||||
return (
|
||||
<header className={cx(option === "logo-left-tinted" ? "bg-brand-tint" : "bg-white", "border-b border-brand/10")}>
|
||||
<div className="cc-wrap flex items-center justify-between gap-6 py-4">
|
||||
<Brand site={site} />
|
||||
<nav aria-label="Main" className="hidden items-center gap-6 md:flex">
|
||||
<Links nav={nav} className="flex gap-5 font-semibold" linkClass="text-gray-800" />
|
||||
{visit && <a href={visit.href} className="cc-btn px-5 py-2">{visit.label}</a>}
|
||||
</nav>
|
||||
<MobileMenu nav={nav} visit={visit} />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
// Clean: small, logo left, text navigation (or a menu on every width).
|
||||
const menuOnly = option === "small-menu";
|
||||
return (
|
||||
<header className="bg-white">
|
||||
<div className="mx-auto flex w-full max-w-5xl items-center justify-between gap-6 px-4 py-5 sm:px-6">
|
||||
<Brand site={site} className="text-lg" />
|
||||
{!menuOnly && (
|
||||
<nav aria-label="Main" className="hidden md:block">
|
||||
<Links nav={nav} className="flex gap-6 text-sm text-gray-700" />
|
||||
</nav>
|
||||
)}
|
||||
<MobileMenu nav={nav} visit={visit} always={menuOnly} />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user