diff --git a/apps/website/CHANGELOG.md b/apps/website/CHANGELOG.md index df9c48d..1c0fdcb 100644 --- a/apps/website/CHANGELOG.md +++ b/apps/website/CHANGELOG.md @@ -34,8 +34,27 @@ `/api/uploads/` (SVGs sandboxed). - **The demo church** (`npm run demo -- --template `): 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): every template's pages pass - axe (WCAG 2.2 AA) and the SEO basics; screenshots at phone and desktop in `e2e/screens/`. +- **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. diff --git a/apps/website/README.md b/apps/website/README.md index 7ed6be9..8ebd9e5 100644 --- a/apps/website/README.md +++ b/apps/website/README.md @@ -8,7 +8,9 @@ section variants and style settings. Changes are drafts until an editor previews 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, publishing, and the demo church. The admin's editing screens are next. Not released; +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 diff --git a/apps/website/backend/src/admin/content.ts b/apps/website/backend/src/admin/content.ts new file mode 100644 index 0000000..f60650b --- /dev/null +++ b/apps/website/backend/src/admin/content.ts @@ -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 { + const out: Record = {}; + for (const i of e.issues) out[i.path.join('.') || '_'] ??= i.message; + return out; +} + +function check(schema: z.ZodType, 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)[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)[type] ?? (BLOCK_SCHEMAS as Record)[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 } }); +} diff --git a/apps/website/backend/src/admin/media.ts b/apps/website/backend/src/admin/media.ts new file mode 100644 index 0000000..0a81d7b --- /dev/null +++ b/apps/website/backend/src/admin/media.ts @@ -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) }; +} diff --git a/apps/website/backend/src/admin/previewLinks.ts b/apps/website/backend/src/admin/previewLinks.ts new file mode 100644 index 0000000..8b01988 --- /dev/null +++ b/apps/website/backend/src/admin/previewLinks.ts @@ -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 { + 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(); +} diff --git a/apps/website/backend/src/admin/routes.ts b/apps/website/backend/src/admin/routes.ts new file mode 100644 index 0000000..748f195 --- /dev/null +++ b/apps/website/backend/src/admin/routes.ts @@ -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; +} diff --git a/apps/website/backend/src/app.ts b/apps/website/backend/src/app.ts index 5250437..275ea28 100644 --- a/apps/website/backend/src/app.ts +++ b/apps/website/backend/src/app.ts @@ -16,13 +16,15 @@ import path from 'node:path'; import express from 'express'; import type { Ctx } from './context.js'; import { authRouter } from './auth/routes.js'; -import { requireRole } from './auth/sessions.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 { siteContent } from './site/content.js'; +import { previewContent, siteContent } from './site/content.js'; import { siteStatus } from './site/status.js'; export function createApp(ctx: Ctx) { @@ -45,6 +47,14 @@ export function createApp(ctx: Ctx) { 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'); @@ -64,11 +74,7 @@ export function createApp(ctx: Ctx) { app.use('/api', authRouter(ctx)); app.use('/api', linksRouter(ctx)); - const admin = express.Router(); - admin.use(express.json({ limit: '256kb' })); - admin.use(requireRole(ctx, 'viewer')); - admin.get('/me', handle(async (req) => ({ user: req.signed!.user, mfa: req.signed!.mfa }))); - app.use('/api/v1/admin', admin); + app.use('/api/v1/admin', adminRouter(ctx)); app.use('/api', (_req, res) => { res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } }); diff --git a/apps/website/backend/src/http.ts b/apps/website/backend/src/http.ts index d36cdc8..d8521e0 100644 --- a/apps/website/backend/src/http.ts +++ b/apps/website/backend/src/http.ts @@ -1,6 +1,6 @@ /** * Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and - * Events' /api/v2) and async handlers. + * Events' /api/v2), async handlers, and a same-origin check on everything that changes something. */ import type { Request, RequestHandler, Response } from 'express'; @@ -19,8 +19,30 @@ export function sendError(res: Response, e: unknown) { return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } }); } -export const handle = (fn: (req: Request, res: Response) => Promise): RequestHandler => (req, res) => { - fn(req, res).then((out) => { +/** 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.' } }); + }; +} diff --git a/apps/website/backend/src/site/content.ts b/apps/website/backend/src/site/content.ts index 2edb33f..120669b 100644 --- a/apps/website/backend/src/site/content.ts +++ b/apps/website/backend/src/site/content.ts @@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT import type { Ctx } from '../context.js'; import { churchProfile } from '../church/profile.js'; import { buildPalette, type Palette } from './palette.js'; -import { mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js'; +import { buildSnapshot, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js'; import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js'; export type SiteEvent = { @@ -51,7 +51,8 @@ export type SiteContent = | (Common & { mode: 'published'; version: number; - snapshot: Snapshot; + /** Without its `source` (the working copy's rows): visitors never get internal ids or hidden sections. */ + snapshot: Omit; /** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */ transparentHeader: Record; messages: SiteMessage[]; @@ -129,8 +130,19 @@ async function liveEvents(ctx: Ctx): Promise { 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 { 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 { + 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 { if (!published) { const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } }); const template = (design?.template ?? 'heritage') as WebsiteTemplate; @@ -139,7 +151,7 @@ export async function siteContent(ctx: Ctx): Promise { comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.', }; } - const { snapshot } = published; + 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; diff --git a/apps/website/backend/src/site/snapshot.ts b/apps/website/backend/src/site/snapshot.ts index f1c03d3..47c9e8a 100644 --- a/apps/website/backend/src/site/snapshot.ts +++ b/apps/website/backend/src/site/snapshot.ts @@ -41,6 +41,8 @@ export type Snapshot = { leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[]; /** Every image the sections refer to, by media id. */ media: Record; + /** 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('/')}`; @@ -62,16 +64,50 @@ export function cleanDesign(saved: { template: string; variants: unknown; home: return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style }; } -/** The working copy as a snapshot. */ -export async function buildSnapshot(ctx: Ctx): Promise { +/** 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, media] = await Promise.all([ + 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' }] }), - db.mediaAsset.findMany(), ]); + return { design, pages, ministries, leaders }; +} + +export function toSource(w: Awaited>): 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 { + 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 = {}; @@ -84,12 +120,12 @@ export async function buildSnapshot(ctx: Ctx): Promise { }; walk(data); }; - const d = cleanDesign(design); - const snapshotPages: SnapshotPage[] = pages.map((p) => { + 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((s) => [s.type, s])); + 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); @@ -98,12 +134,12 @@ export async function buildSnapshot(ctx: Ctx): Promise { sections.push({ type: entry.section, variant: d.variants[entry.section], data }); } } else { - for (const s of p.sections) { - if (s.hidden) continue; - const data = parseSectionData(s.type, s.data); + 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: s.type, variant: s.variant, data }); + sections.push({ type: x.type, variant: x.variant, data }); } } return { @@ -115,9 +151,10 @@ export async function buildSnapshot(ctx: Ctx): Promise { v: SNAPSHOT_VERSION, design: d, pages: snapshotPages, - ministries: ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })), - leaders: leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })), + 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, }; } diff --git a/apps/website/backend/src/site/workingCopy.ts b/apps/website/backend/src/site/workingCopy.ts new file mode 100644 index 0000000..0ff555d --- /dev/null +++ b/apps/website/backend/src/site/workingCopy.ts @@ -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 { + const m = new Map(); + 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)[k])}`).join(',')}}`; + return JSON.stringify(v ?? null); +} + +async function publishedSource(ctx: Ctx): Promise { + return (await publishedSnapshot(ctx))?.snapshot.source ?? null; +} + +export async function changes(ctx: Ctx): Promise { + 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(); + 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 }; +} diff --git a/apps/website/backend/tests/admin.test.ts b/apps/website/backend/tests/admin.test.ts new file mode 100644 index 0000000..a24430f --- /dev/null +++ b/apps/website/backend/tests/admin.test.ts @@ -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('')), 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('')); + 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); + }); +}); diff --git a/apps/website/e2e/admin.spec.ts b/apps/website/e2e/admin.spec.ts new file mode 100644 index 0000000..db38a71 --- /dev/null +++ b/apps/website/e2e/admin.spec.ts @@ -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([]); + } +}); diff --git a/apps/website/e2e/server.ts b/apps/website/e2e/server.ts index e538130..007b615 100644 --- a/apps/website/e2e/server.ts +++ b/apps/website/e2e/server.ts @@ -15,6 +15,7 @@ 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'; @@ -43,5 +44,14 @@ app.post('/test/design', express.json(), async (req, res) => { 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.')); diff --git a/apps/website/env.template.json b/apps/website/env.template.json index ecfa148..d81ffe7 100644 --- a/apps/website/env.template.json +++ b/apps/website/env.template.json @@ -18,7 +18,8 @@ { "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_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" } ] } } diff --git a/apps/website/frontend/src/admin/ListEditor.tsx b/apps/website/frontend/src/admin/ListEditor.tsx new file mode 100644 index 0000000..f706474 --- /dev/null +++ b/apps/website/frontend/src/admin/ListEditor.tsx @@ -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 & { id: string }; + +function Editor({ fields, initial, onSave, onCancel, busy, errors }: { fields: ListField[]; initial: Row | Record; onSave: (v: Record) => void; onCancel: () => void; busy: boolean; errors: Record }) { + const [v, setV] = useState>(initial); + return ( +
+ {fields.map((f) => f.kind === "image" + ? setV({ ...v, [f.key]: id })} /> + : ( + + {f.kind === "text" + ? setV({ ...v, [f.key]: e.target.value || null })} /> + :